|
| 1 | +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; |
| 2 | +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; |
| 3 | +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; |
| 4 | +import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; |
| 5 | +import * as z from 'zod'; |
| 6 | + |
| 7 | +export default { |
| 8 | + async fetch(_request, _env, _ctx) { |
| 9 | + // Not wrapped with `wrapMcpServerWithSentry`: the vite plugin instruments `McpServer`. |
| 10 | + const server = new McpServer({ name: 'mcp-server-worker', version: '1.0.0' }); |
| 11 | + server.registerTool('echo', { inputSchema: { message: z.string() } }, async ({ message }) => ({ |
| 12 | + content: [{ type: 'text' as const, text: `Echo: ${message}` }], |
| 13 | + })); |
| 14 | + server.registerTool('returns-error', {}, async () => ({ |
| 15 | + isError: true, |
| 16 | + content: [{ type: 'text' as const, text: 'Upstream returned 500.' }], |
| 17 | + })); |
| 18 | + |
| 19 | + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); |
| 20 | + await server.connect(serverTransport); |
| 21 | + // The default validator compiles schemas with `new Function`, which workerd does not allow. |
| 22 | + const client = new Client( |
| 23 | + { name: 'test-client', version: '1.0.0' }, |
| 24 | + { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }, |
| 25 | + ); |
| 26 | + await client.connect(clientTransport); |
| 27 | + |
| 28 | + const tools = await client.listTools(); |
| 29 | + const echo = await client.callTool({ name: 'echo', arguments: { message: 'hi' } }); |
| 30 | + const failed = await client.callTool({ name: 'returns-error', arguments: {} }); |
| 31 | + const feedback = await client.callTool({ |
| 32 | + name: 'submit_feedback', |
| 33 | + arguments: { task: 'report from an agent', kind: 'idea', impact: 'friction', description: 'From a worker.' }, |
| 34 | + }); |
| 35 | + await client.close(); |
| 36 | + |
| 37 | + return Response.json({ |
| 38 | + tools: tools.tools.map(tool => tool.name), |
| 39 | + echo: echo.content, |
| 40 | + failed: failed.content, |
| 41 | + feedback: feedback.content, |
| 42 | + }); |
| 43 | + }, |
| 44 | +} satisfies ExportedHandler; |
0 commit comments