Open History to see the last commit
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>
14}
15
16const ACTIVITIES = [
17 'chat',
18 'image',
19 'video',
20 'audio',
21 'embeddings',
22 'moderation',
23]
24
25export const WEBMCP_TOOLS: Array<WebMcpToolDefinition> = [
26 {
27 name: 'list_models',
28 description:
29 'Cross-provider model catalog: which AI models exist right now, filterable by activity (chat/image/video/audio/embeddings/moderation), provider, capability flag (a flag the model is stated to support, e.g. tools), or free text.',
30 inputSchema: {
31 type: 'object',
32 properties: {
33 activity: { type: 'string', enum: ACTIVITIES },
34 provider: { type: 'string' },
35 capability: { type: 'string' },
36 q: { type: 'string' },
37 },
38 },
39 },
40 {
41 name: 'list_schemas',
42 description:
43 '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.',
44 inputSchema: {
45 type: 'object',
46 properties: {
47 provider: {
48 type: 'string',
49 description: 'Optional provider id to narrow the index.',
50 },
51 },
52 },
53 },
54 {
55 name: 'get_schema',
56 description:
57 'Self-contained JSON Schema ($defs-bundled) for a provider endpoint — request (input) or response (output) shape.',
58 inputSchema: {
59 type: 'object',
60 properties: {
61 provider: { type: 'string' },
62 activity: { type: 'string', enum: ACTIVITIES },
63 endpointId: {
64 type: 'string',
65 description:
66 "Path-derived id (e.g. 'v1/messages' or 'chat/completions') or a listed model rawId, which aliases onto that activity's generation route.",
67 },
68 kind: { type: 'string', enum: ['input', 'output'] },
69 version: {
70 type: 'string',
71 description: 'Content hash of a historical version.',
72 },
73 },
74 required: ['provider', 'activity', 'endpointId'],
75 },
76 },
77 {
78 name: 'validate_payload',
79 description:
80 'Validate a request/response payload against the current stored schema for a provider endpoint before spending tokens on a real call.',
81 inputSchema: {
82 type: 'object',
83 properties: {
84 provider: { type: 'string' },
85 endpointId: { type: 'string' },
86 kind: { type: 'string', enum: ['input', 'output'] },
87 payload: { description: 'The payload to validate.' },
88 },
89 required: ['provider', 'endpointId', 'payload'],
90 },
91 },
92]
93
94interface ModelContextTool extends WebMcpToolDefinition {
95 execute: (args: Record<string, unknown>) => Promise<unknown>
96}
97
98interface ModelContext {
99 provideContext: (context: { tools: Array<ModelContextTool> }) => void
100}
101
102/** Each tool call is a JSON-RPC tools/call against our own /mcp endpoint,
103 * so WebMCP results are byte-identical to remote MCP results. */
104async function callMcpTool(
105 name: string,
106 args: Record<string, unknown>,
107): Promise<unknown> {
108 const response = await fetch('/mcp', {
109 method: 'POST',
110 headers: { 'Content-Type': 'application/json' },
111 body: JSON.stringify({
112 jsonrpc: '2.0',
113 id: 1,
114 method: 'tools/call',
115 params: { name, arguments: args },
116 }),
117 })
118 const body = (await response.json()) as {
119 result?: unknown
120 error?: unknown
121 }
122 return body.result ?? body.error
123}
124
125/** Registers the tools when navigator.modelContext exists; no-op (false)
126 * everywhere else. Safe to call during SSR. */
127export function registerWebMcp(): boolean {
128 if (typeof navigator === 'undefined') return false
129 const modelContext = (navigator as { modelContext?: ModelContext })
130 .modelContext
131 if (typeof modelContext?.provideContext !== 'function') return false
132 modelContext.provideContext({
133 tools: WEBMCP_TOOLS.map((tool) => ({
134 ...tool,
135 execute: (args: Record<string, unknown>) => callMcpTool(tool.name, args),
136 })),
137 })
138 return true
139}