|
| 1 | +--- |
| 2 | +title: MCP sample - CLI |
| 3 | +summary: A basic MCP sample for CLI with typescript |
| 4 | +date: "2025-04-25" |
| 5 | +slug: mcp-cli |
| 6 | +tags: |
| 7 | + - typescript |
| 8 | + - ai |
| 9 | + - mcp |
| 10 | +--- |
| 11 | + |
| 12 | +The idea here is not explain what MCP is, just show a sample: |
| 13 | + |
| 14 | +# Dependencies |
| 15 | + |
| 16 | +Install it with npm/yarn/pnpm: |
| 17 | + |
| 18 | +- @modelcontextprotocol/sdk |
| 19 | +- zod |
| 20 | + |
| 21 | +# Code |
| 22 | + |
| 23 | +```typescript |
| 24 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 25 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 26 | +import { |
| 27 | + CallToolRequestSchema, |
| 28 | + ListToolsRequestSchema, |
| 29 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 30 | +import { z } from "zod"; |
| 31 | + |
| 32 | +const tools = [ |
| 33 | + { |
| 34 | + name: "Sum", |
| 35 | + description: "do a sum", |
| 36 | + inputSchema: z.object({ x: z.number(), y: z.number() }), |
| 37 | + handler: (args) => ({ |
| 38 | + content: [ |
| 39 | + { type: "text", text: `${args.x} + ${args.y} = ${args.x + args.y}` }, |
| 40 | + ], |
| 41 | + }), |
| 42 | + }, |
| 43 | +]; |
| 44 | + |
| 45 | +const server = new Server( |
| 46 | + { name: "mcp-server", version: "0.0.1" }, |
| 47 | + { capabilities: { tools: {} } } |
| 48 | +); |
| 49 | +server.setRequestHandler(ListToolsRequestSchema, async () => { |
| 50 | + return { |
| 51 | + tools: tools.map((t) => ({ |
| 52 | + name: t.name, |
| 53 | + description: t.description, |
| 54 | + parameters: t.inputSchema, |
| 55 | + })), |
| 56 | + }; |
| 57 | +}); |
| 58 | + |
| 59 | +server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 60 | + const { name, arguments: args } = request.params; |
| 61 | + |
| 62 | + try { |
| 63 | + const tool = tools.find((t) => t.name === name); |
| 64 | + if (!tool) { |
| 65 | + throw new Error(`Tool unknown: ${name}`); |
| 66 | + } |
| 67 | + return await tool.handler(args); |
| 68 | + } catch (error) { |
| 69 | + console.error(`Error executing tool ${name}:`, error); |
| 70 | + throw error; |
| 71 | + } |
| 72 | +}); |
| 73 | + |
| 74 | +const main = async () => { |
| 75 | + const transport = new StdioServerTransport(); |
| 76 | + await server.connect(transport); |
| 77 | +}; |
| 78 | + |
| 79 | +main(); |
| 80 | +``` |
| 81 | + |
| 82 | +# Sample calling |
| 83 | + |
| 84 | +List tools: |
| 85 | + |
| 86 | +```sh |
| 87 | +echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | pnpm dlx tsx cli.ts |
| 88 | +``` |
| 89 | + |
| 90 | +Executing operation: |
| 91 | + |
| 92 | +```sh |
| 93 | +echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "Sum", "arguments": {"x": 1, "y": 2}}}' | pnpm dlx tsx cli.ts |
| 94 | +``` |
0 commit comments