-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcustomMethodExample.ts
More file actions
42 lines (35 loc) · 1.64 KB
/
customMethodExample.ts
File metadata and controls
42 lines (35 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env node
/**
* Registering vendor-specific (non-spec) JSON-RPC methods on a `Server`.
*
* Custom methods use the Zod-schema form of `setRequestHandler` / `setNotificationHandler`:
* pass a Zod object schema whose `method` field is `z.literal('<method>')`. The same overload
* is available on `Client` (for server→client custom methods).
*
* To call these from the client side, use:
* await client.request({ method: 'acme/search', params: { query: 'widgets' } }, SearchResult)
* await client.notification({ method: 'acme/tick', params: { n: 1 } })
* See examples/client/src/customMethodExample.ts.
*/
import { Server, StdioServerTransport } from '@modelcontextprotocol/server';
import { z } from 'zod';
const SearchRequest = z.object({
method: z.literal('acme/search'),
params: z.object({ query: z.string() })
});
const TickNotification = z.object({
method: z.literal('acme/tick'),
params: z.object({ n: z.number() })
});
const server = new Server({ name: 'custom-method-server', version: '1.0.0' }, { capabilities: {} });
server.setRequestHandler(SearchRequest, async (request, ctx) => {
console.error('[server] acme/search query=' + request.params.query);
await ctx.mcpReq.notify({ method: 'acme/searchProgress', params: { stage: 'start', pct: 0 } });
const hits = [request.params.query, request.params.query + '-result'];
await ctx.mcpReq.notify({ method: 'acme/searchProgress', params: { stage: 'done', pct: 100 } });
return { hits };
});
server.setNotificationHandler(TickNotification, n => {
console.error('[server] acme/tick n=' + n.params.n);
});
await server.connect(new StdioServerTransport());