Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

webmcp.ts

142 lines4.4 KB

1/**
2 * WebMCP (PLAN.md task 10.6): when the browser exposes the draft
3 * `navigator.modelContext` API, register in-page tools wrapping the public
4 * API so an embedded agent can use the service without leaving the page.
5 * Definitions are literal copies of the server MCP tools (no server imports
6 * — keeps drizzle/workers code out of the client bundle); a unit test pins
7 * them to src/server/mcp.ts TOOLS so they cannot drift.
8 */
9​
10export interface WebMcpToolDefinition {
11 name: string
12 description: string
13 inputSchema: Record<string, unknown>
15​
16const ACTIVITIES = [
17 'chat',
18 'image',
19 'video',
20 'audio',
21 'embeddings',
22 'moderation',
23 'world',
24 'decision',
25 'search',
27​
28export const WEBMCP_TOOLS: Array<WebMcpToolDefinition> = [
29 {
30 name: 'list_models',
31 description:
32 'Cross-provider model catalog: which AI models exist right now, filterable by activity (chat/image/video/audio/embeddings/moderation/world/decision/search), provider, capability flag (a flag the model is stated to support, e.g. tools), or free text.',
33 inputSchema: {
34 type: 'object',
35 properties: {
36 activity: { type: 'string', enum: ACTIVITIES },
37 provider: { type: 'string' },
38 capability: { type: 'string' },
39 q: { type: 'string' },
40 },
41 },
42 },
43 {
44 name: 'list_schemas',
45 description:
46 'Index of every schema on the system: provider → activity → endpoint ids. Pass provider to narrow to one provider. Use it to discover valid get_schema arguments.',
47 inputSchema: {
48 type: 'object',
49 properties: {
50 provider: {
51 type: 'string',
52 description: 'Optional provider id to narrow the index.',
53 },
54 },
55 },
56 },
57 {
58 name: 'get_schema',
59 description:
60 'Self-contained JSON Schema ($defs-bundled) for a provider endpoint — request (input) or response (output) shape.',
61 inputSchema: {
62 type: 'object',
63 properties: {
64 provider: { type: 'string' },
65 activity: { type: 'string', enum: ACTIVITIES },
66 endpointId: {
67 type: 'string',
68 description:
69 "Path-derived id (e.g. 'v1/messages' or 'chat/completions') or a listed model rawId, which aliases onto that activity's generation route.",
70 },
71 kind: { type: 'string', enum: ['input', 'output'] },
72 version: {
73 type: 'string',
74 description: 'Content hash of a historical version.',
75 },
76 },
77 required: ['provider', 'activity', 'endpointId'],
78 },
79 },
80 {
81 name: 'validate_payload',
82 description:
83 'Validate a request/response payload against the current stored schema for a provider endpoint before spending tokens on a real call.',
84 inputSchema: {
85 type: 'object',
86 properties: {
87 provider: { type: 'string' },
88 endpointId: { type: 'string' },
89 kind: { type: 'string', enum: ['input', 'output'] },
90 payload: { description: 'The payload to validate.' },
91 },
92 required: ['provider', 'endpointId', 'payload'],
93 },
94 },
96​
97interface ModelContextTool extends WebMcpToolDefinition {
98 execute: (args: Record<string, unknown>) => Promise<unknown>
100​
101interface ModelContext {
102 provideContext: (context: { tools: Array<ModelContextTool> }) => void
104​
105/** Each tool call is a JSON-RPC tools/call against our own /mcp endpoint,
106 * so WebMCP results are byte-identical to remote MCP results. */
107async function callMcpTool(
108 name: string,
109 args: Record<string, unknown>,
110): Promise<unknown> {
111 const response = await fetch('/mcp', {
112 method: 'POST',
113 headers: { 'Content-Type': 'application/json' },
114 body: JSON.stringify({
115 jsonrpc: '2.0',
116 id: 1,
117 method: 'tools/call',
118 params: { name, arguments: args },
119 }),
120 })
121 const body = (await response.json()) as {
122 result?: unknown
123 error?: unknown
124 }
125 return body.result ?? body.error
127​
128/** Registers the tools when navigator.modelContext exists; no-op (false)
129 * everywhere else. Safe to call during SSR. */
130export function registerWebMcp(): boolean {
131 if (typeof navigator === 'undefined') return false
132 const modelContext = (navigator as { modelContext?: ModelContext })
133 .modelContext
134 if (typeof modelContext?.provideContext !== 'function') return false
135 modelContext.provideContext({
136 tools: WEBMCP_TOOLS.map((tool) => ({
137 ...tool,
138 execute: (args: Record<string, unknown>) => callMcpTool(tool.name, args),
139 })),
140 })
141 return true