{"_id":"@edgen-ai/rpc-tool","name":"@edgen-ai/rpc-tool","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@edgen-ai/rpc-tool","version":"1.0.0","main":"dist/index.js","types":"dist/index.d.ts","publishConfig":{"access":"public"},"keywords":[],"description":"LangChain StructuredTools JSON-RPC Server","dependencies":{"@langchain/core":"^0.3.43","@open-rpc/client-js":"1.8.1","@open-rpc/meta-schema":"1.14.9","@open-rpc/server-js":"1.9.5"},"devDependencies":{"ts-node":"^10.9.2","@edgen-ai/tools":"1.0.0","@edgen-ai/tsconfig":"1.0.0"},"scripts":{"build":"tsc"},"_id":"@edgen-ai/rpc-tool@1.0.0","_integrity":"sha512-feIFeG7VJzMmbMfSwcwLOHXuRXl94YImCHnRVJxMLqcWg6EKxpypkcsMuf/qjk4y3ADxVudBAbLGX4TPvGs67g==","_resolved":"/private/var/folders/sl/w723smm154gd8sky2734vdfr0000gp/T/1f1ece91016173d37ce772342c2b10bc/edgen-ai-rpc-tool-1.0.0.tgz","_from":"file:edgen-ai-rpc-tool-1.0.0.tgz","_nodeVersion":"20.18.1","_npmVersion":"10.8.2","dist":{"integrity":"sha512-feIFeG7VJzMmbMfSwcwLOHXuRXl94YImCHnRVJxMLqcWg6EKxpypkcsMuf/qjk4y3ADxVudBAbLGX4TPvGs67g==","shasum":"fe6d4a2ee498d75fe731372c309d4b0b7bae0688","tarball":"https://registry.npmjs.org/@edgen-ai/rpc-tool/-/rpc-tool-1.0.0.tgz","fileCount":11,"unpackedSize":32417,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCICekUQFEVMefnOu2Ar27kOeTh9uyHj92KjJXwP2OpQ6NAiEAiPCTIuiC3rNB3VKorn8GR2WOhkvVyEegmmjulvGLExI="}]},"_npmUser":{"name":"zhanxinxu-evg","email":"zhanxin.xu@kikitrade.com"},"directories":{},"maintainers":[{"name":"zhanxinxu-evg","email":"zhanxin.xu@kikitrade.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/rpc-tool_1.0.0_1745482562075_0.08020619448715527"},"_hasShrinkwrap":false}},"time":{"created":"2025-04-24T08:16:02.009Z","1.0.0":"2025-04-24T08:16:02.336Z","modified":"2025-04-24T08:16:02.571Z"},"maintainers":[{"name":"zhanxinxu-evg","email":"zhanxin.xu@kikitrade.com"}],"description":"LangChain StructuredTools JSON-RPC Server","keywords":[],"readme":"# LangChain StructuredTools JSON-RPC Server\n\nA powerful and flexible JSON-RPC server that exposes LangChain's StructuredTools as JSON-RPC endpoints. This package enables seamless integration between LangChain tools and any application that supports JSON-RPC 2.0, allowing you to leverage AI tools in various environments.\n\n## Features\n\n- **Automatic Tool Conversion**: Transforms LangChain StructuredTools into JSON-RPC methods with preserved metadata\n- **Dual Transport Support**: Offers both HTTP and WebSocket interfaces for flexible integration\n- **Schema Validation**: Validates parameters using Zod schemas from the original tools\n- **OpenRPC Discovery**: Implements the `rpc.discover` method for automatic API documentation\n- **Comprehensive Error Handling**: Provides detailed error messages with appropriate error codes\n- **CORS Support**: Enables cross-origin requests for web applications\n- **Bidirectional Communication**: Supports both client-to-server and server-to-client communication via WebSockets\n- **Request Logging**: Includes built-in logging for debugging and monitoring\n\n## Installation\n\n```bash\n# Install the package\nnpm install @edgen-ai/rpc-tool\n\n# Install peer dependencies if not already installed\nnpm install @langchain/core @open-rpc/server-js @open-rpc/client-js\n```\n\n## Usage\n\n### Server-Side: Exposing LangChain Tools\n\n```typescript\nimport { StructuredToolsRPCServer } from '@edgen-ai/rpc-tool';\nimport { TACalculateTool, ArtemisMetricsTool } from '@edgen-ai/tools';\n\nasync function startServer() {\n  // Collect all StructuredTools you want to expose\n  const tools = [\n    new TACalculateTool(),\n    new ArtemisMetricsTool('YOUR_API_KEY')\n  ];\n\n  // Create and start the RPC server\n  const rpcServer = new StructuredToolsRPCServer(tools);\n  \n  // Configure ports and host\n  const httpPort = 3030;\n  const wsPort = 3031;\n  const host = '0.0.0.0';  // Use 0.0.0.0 to listen on all interfaces\n  \n  await rpcServer.start(httpPort, wsPort, host);\n  \n  console.log(`Server running at http://${host}:${httpPort} and ws://${host}:${wsPort}`);\n}\n\nstartServer();\n```\n\n### Client-Side: Consuming JSON-RPC Tools\n\n#### HTTP Client Example\n\n```typescript\nimport { Client, HTTPTransport, RequestManager } from \"@open-rpc/client-js\";\n\n// Create client with HTTP transport\nconst client = new Client(new RequestManager([new HTTPTransport(\"http://localhost:3030\")]));\n\n/**\n * Example: Call the TA Calculate tool\n */\nasync function exampleTaCalculate() {\n  try {\n    const result = await client.request({\n      method: 'ta-calculate',\n      params: [{\n        in_real: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n        rsi: {\n          opt_in_time_period: 5\n        }\n      }]\n    });\n\n    console.log('TA Calculate Result:');\n    console.log(JSON.stringify(result, null, 2));\n  } catch (error) {\n    console.error('Error calling ta-calculate:', error);\n  }\n}\n\n// Get OpenRPC document for API discovery\nasync function getOpenRPCDocument() {\n  const result = await client.request({\n    method: 'rpc.discover',\n    params: []\n  });\n  return result;\n}\n\n// Run the examples\nasync function runExamples() {\n  console.log('Running JSON-RPC client examples...');\n  // Get OpenRPC document\n  const openrpcDocument = await getOpenRPCDocument();\n  console.log('OpenRPC Document:', JSON.stringify(openrpcDocument, null, 2));\n  // Run the examples\n  await exampleTaCalculate();\n  console.log('Examples completed.');\n}\n\nrunExamples().catch(console.error);\n```\n\n#### WebSocket Client Example\n\n```typescript\nimport { Client, WebSocketTransport, RequestManager } from \"@open-rpc/client-js\";\n\n// Create client with WebSocket transport\nconst client = new Client(new RequestManager([new WebSocketTransport(\"ws://localhost:3031\")]));\n\n// The rest of the code is the same as the HTTP example\nasync function exampleTaCalculate() {\n  try {\n    const result = await client.request({\n      method: 'ta-calculate',\n      params: [{\n        in_real: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n        rsi: {\n          opt_in_time_period: 5\n        }\n      }]\n    });\n\n    console.log('TA Calculate Result:');\n    console.log(JSON.stringify(result, null, 2));\n  } catch (error) {\n    console.error('Error calling ta-calculate:', error);\n  }\n}\n```\n\n#### Using the RPC Tool Generator\n\nThe package also provides a client-side tool generator that can automatically create LangChain tools from a remote JSON-RPC server:\n\n```typescript\nimport Client, { HTTPTransport, RequestManager } from \"@open-rpc/client-js\";\nimport { RpcToolGenerator } from \"@edgen-ai/rpc-tool\";\n\n// Create a client connected to the RPC server and generate tools\nnew RpcToolGenerator({\n    client: new Client(new RequestManager([new HTTPTransport(\"http://localhost:3030\")]))\n}).generateRpcTools().then((tools) => {\n    console.log(`Generated ${tools.length} tools from the server`);\n    \n    // Example: Call the TA Calculate tool\n    tools.filter((tool) => tool.name === 'ta-calculate')[0].invoke({\n        in_real: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n        rsi: {\n            opt_in_time_period: 5\n        }\n    }).then((result) => {\n        console.log(result);\n    });\n});\n```\n\n### Environment Variables\n\nYou can configure the server using the following environment variables:\n\n| Variable | Description | Default |\n|----------|-------------|----------|\n| `JSON_RPC_PORT` | HTTP port for the JSON-RPC server | 3030 |\n| `JSON_RPC_WS_PORT` | WebSocket port for the JSON-RPC server | 3031 |\n| `JSON_RPC_HOST` | Host address to bind the server | 0.0.0.0 |\n\n## Architecture\n\nThe package consists of three main components:\n\n1. **StructuredToolsRPCServer**: Core server that converts LangChain tools to JSON-RPC methods\n2. **RPCTool**: Client-side representation of a remote JSON-RPC method as a LangChain tool\n3. **RpcToolGenerator**: Utility to discover and generate client tools from a remote server\n\n## OpenRPC Discovery\n\nThe server implements the standard `rpc.discover` method, which returns an OpenRPC document describing all available methods. This enables automatic documentation and client code generation.\n\nTo view the API documentation, send a request to the `rpc.discover` method:\n\n```javascript\nconst response = await fetch('http://localhost:3030', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({\n    jsonrpc: '2.0',\n    id: 1,\n    method: 'rpc.discover',\n    params: []\n  }),\n});\n\nconst apiDoc = await response.json();\nconsole.log(apiDoc.result);\n```\n\n## Error Handling\n\nThe server provides detailed error messages following the JSON-RPC 2.0 specification:\n\n| Error Code | Description |\n|------------|-------------|\n| -32600 | Invalid Request |\n| -32601 | Method not found |\n| -32602 | Invalid params (validation errors) |\n| -32000 | Server error |\n\nError responses include detailed information to help diagnose issues:\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"error\": {\n    \"code\": -32602,\n    \"message\": \"Parameter validation failed: data: Required\",\n    \"data\": {\n      \"details\": [\n        {\n          \"path\": [\"data\"],\n          \"message\": \"Required\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Advanced Configuration\n\nYou can customize the server by providing additional options to the `StructuredToolsRPCServer` constructor:\n\n```typescript\nconst rpcServer = new StructuredToolsRPCServer(tools, {\n  openrpcDocument: {\n    openrpc: '1.2.6',\n    info: {\n      title: 'Custom API Title',\n      version: '2.0.0',\n      description: 'Custom API description'\n    },\n    methods: [] // Will be populated automatically\n  }\n});\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n","readmeFilename":"README.md","_rev":"1-d2983ff287ba54b65b5ccf08bbaae4e5"}