@slotform/api 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/client.d.ts +16 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +98 -0
- package/dist/client.js.map +1 -0
- package/dist/error.d.ts +2 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/error.js +2 -0
- package/dist/error.js.map +1 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +640 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/chosen.d.ts +12 -0
- package/dist/lib/chosen.d.ts.map +1 -0
- package/dist/lib/chosen.js +18 -0
- package/dist/lib/chosen.js.map +1 -0
- package/dist/lib/cursor.d.ts +68 -0
- package/dist/lib/cursor.d.ts.map +1 -0
- package/dist/lib/cursor.js +220 -0
- package/dist/lib/cursor.js.map +1 -0
- package/dist/lib/limits.d.ts +4 -0
- package/dist/lib/limits.d.ts.map +1 -0
- package/dist/lib/limits.js +10 -0
- package/dist/lib/limits.js.map +1 -0
- package/dist/lib/local-origin.d.ts +2 -0
- package/dist/lib/local-origin.d.ts.map +1 -0
- package/dist/lib/local-origin.js +17 -0
- package/dist/lib/local-origin.js.map +1 -0
- package/dist/lib/slugify.d.ts +4 -0
- package/dist/lib/slugify.d.ts.map +1 -0
- package/dist/lib/slugify.js +26 -0
- package/dist/lib/slugify.js.map +1 -0
- package/dist/lib/window.d.ts +52 -0
- package/dist/lib/window.d.ts.map +1 -0
- package/dist/lib/window.js +70 -0
- package/dist/lib/window.js.map +1 -0
- package/dist/mcp-path.d.ts +2 -0
- package/dist/mcp-path.d.ts.map +1 -0
- package/dist/mcp-path.js +3 -0
- package/dist/mcp-path.js.map +1 -0
- package/dist/mcp.d.ts +15 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +5 -0
- package/dist/mcp.js.map +1 -0
- package/dist/node/barrel.d.ts +3 -0
- package/dist/node/barrel.d.ts.map +1 -0
- package/dist/node/barrel.js +70 -0
- package/dist/node/barrel.js.map +1 -0
- package/dist/node/codegen.d.ts +10 -0
- package/dist/node/codegen.d.ts.map +1 -0
- package/dist/node/codegen.js +132 -0
- package/dist/node/codegen.js.map +1 -0
- package/dist/node/procedure-codegen.d.ts +14 -0
- package/dist/node/procedure-codegen.d.ts.map +1 -0
- package/dist/node/procedure-codegen.js +95 -0
- package/dist/node/procedure-codegen.js.map +1 -0
- package/dist/node/schema-child.d.ts +2 -0
- package/dist/node/schema-child.d.ts.map +1 -0
- package/dist/node/schema-child.js +31 -0
- package/dist/node/schema-child.js.map +1 -0
- package/dist/node/schema-source.d.ts +3 -0
- package/dist/node/schema-source.d.ts.map +1 -0
- package/dist/node/schema-source.js +33 -0
- package/dist/node/schema-source.js.map +1 -0
- package/dist/node/server-client.d.ts +19 -0
- package/dist/node/server-client.d.ts.map +1 -0
- package/dist/node/server-client.js +45 -0
- package/dist/node/server-client.js.map +1 -0
- package/dist/node/types.d.ts +42 -0
- package/dist/node/types.d.ts.map +1 -0
- package/dist/node/types.js +13 -0
- package/dist/node/types.js.map +1 -0
- package/dist/not-found.d.ts +2 -0
- package/dist/not-found.d.ts.map +1 -0
- package/dist/not-found.js +6 -0
- package/dist/not-found.js.map +1 -0
- package/dist/procedure.d.ts +188 -0
- package/dist/procedure.d.ts.map +1 -0
- package/dist/procedure.js +392 -0
- package/dist/procedure.js.map +1 -0
- package/dist/query-invalidation.d.ts +20 -0
- package/dist/query-invalidation.d.ts.map +1 -0
- package/dist/query-invalidation.js +66 -0
- package/dist/query-invalidation.js.map +1 -0
- package/dist/schema.d.ts +32 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +103 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wire.d.ts +11 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +26 -0
- package/dist/wire.js.map +1 -0
- package/dist/worker/guards.d.ts +6 -0
- package/dist/worker/guards.d.ts.map +1 -0
- package/dist/worker/guards.js +29 -0
- package/dist/worker/guards.js.map +1 -0
- package/dist/worker/index.d.ts +57 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +418 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/mcp.d.ts +28 -0
- package/dist/worker/mcp.d.ts.map +1 -0
- package/dist/worker/mcp.js +361 -0
- package/dist/worker/mcp.js.map +1 -0
- package/dist/worker/request-log.d.ts +10 -0
- package/dist/worker/request-log.d.ts.map +1 -0
- package/dist/worker/request-log.js +37 -0
- package/dist/worker/request-log.js.map +1 -0
- package/guide/add-a-procedure.md +42 -0
- package/guide/background.md +86 -0
- package/guide/client.md +93 -0
- package/guide/config.md +85 -0
- package/guide/mcp.md +68 -0
- package/guide/middleware.md +79 -0
- package/guide/procedures.md +95 -0
- package/guide/utilities.md +135 -0
- package/package.json +120 -3
- package/src/client.ts +129 -0
- package/src/error.ts +1 -0
- package/src/index.ts +787 -0
- package/src/lib/chosen.ts +31 -0
- package/src/lib/cursor.ts +354 -0
- package/src/lib/limits.ts +10 -0
- package/src/lib/local-origin.ts +18 -0
- package/src/lib/slugify.ts +29 -0
- package/src/lib/window.ts +155 -0
- package/src/mcp-path.ts +2 -0
- package/src/mcp.ts +30 -0
- package/src/node/barrel.ts +77 -0
- package/src/node/codegen.ts +173 -0
- package/src/node/procedure-codegen.ts +131 -0
- package/src/node/schema-child.ts +31 -0
- package/src/node/schema-source.ts +45 -0
- package/src/node/server-client.ts +67 -0
- package/src/node/types.ts +64 -0
- package/src/not-found.ts +6 -0
- package/src/procedure.ts +935 -0
- package/src/query-invalidation.ts +106 -0
- package/src/schema.ts +133 -0
- package/src/types.ts +72 -0
- package/src/wire.ts +34 -0
- package/src/worker/guards.ts +37 -0
- package/src/worker/index.ts +681 -0
- package/src/worker/mcp.ts +470 -0
- package/src/worker/request-log.ts +50 -0
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AuthInfo,
|
|
3
|
+
CallToolResult,
|
|
4
|
+
McpHttpHandler,
|
|
5
|
+
McpRequestContext,
|
|
6
|
+
Tool,
|
|
7
|
+
} from "@modelcontextprotocol/server";
|
|
8
|
+
import { call, isProcedure, ORPCError } from "@orpc/server";
|
|
9
|
+
import type { Context } from "hono";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import type { McpDefinition } from "../mcp.ts";
|
|
12
|
+
import { MCP_PATH } from "../mcp-path.ts";
|
|
13
|
+
import { inputJsonSchema } from "../schema.ts";
|
|
14
|
+
import { ipLimited, isForbiddenOrigin } from "./guards.ts";
|
|
15
|
+
|
|
16
|
+
// The MCP endpoint: `POST /mcp` over the consumer's procedures. The SDK loads
|
|
17
|
+
// on the first request, so a worker without `src/worker/mcp.ts` never reads it.
|
|
18
|
+
|
|
19
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
20
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
21
|
+
const SERVER_VERSION = "1.0.0";
|
|
22
|
+
const INTERNAL = {
|
|
23
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
24
|
+
message: "Internal server error",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
interface McpTool {
|
|
28
|
+
name: string;
|
|
29
|
+
description: string;
|
|
30
|
+
inputSchema: Tool["inputSchema"];
|
|
31
|
+
readOnly: boolean;
|
|
32
|
+
procedure: Parameters<typeof call>[0];
|
|
33
|
+
// Turns each string at a `z.date()` position into the `Date` it spells.
|
|
34
|
+
convert: (args: unknown) => unknown;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type Convert = (value: unknown) => unknown;
|
|
38
|
+
|
|
39
|
+
// The schemas a walk of `def` reaches below the one holding it.
|
|
40
|
+
function children(schema: z.ZodType): z.ZodType[] {
|
|
41
|
+
// zod's `def` is a union keyed by `type`; the walk reads each member's own fields by name.
|
|
42
|
+
const def = schema._zod.def as unknown as Record<string, unknown>;
|
|
43
|
+
const found: unknown[] = [];
|
|
44
|
+
switch (def.type) {
|
|
45
|
+
case "object":
|
|
46
|
+
found.push(...Object.values(def.shape as Record<string, unknown>));
|
|
47
|
+
break;
|
|
48
|
+
case "array":
|
|
49
|
+
found.push(def.element);
|
|
50
|
+
break;
|
|
51
|
+
case "optional":
|
|
52
|
+
case "nullable":
|
|
53
|
+
case "default":
|
|
54
|
+
case "prefault":
|
|
55
|
+
case "nonoptional":
|
|
56
|
+
case "readonly":
|
|
57
|
+
case "catch":
|
|
58
|
+
found.push(def.innerType);
|
|
59
|
+
break;
|
|
60
|
+
case "union":
|
|
61
|
+
found.push(...(def.options as unknown[]));
|
|
62
|
+
break;
|
|
63
|
+
case "pipe":
|
|
64
|
+
found.push(def.in);
|
|
65
|
+
break;
|
|
66
|
+
case "record":
|
|
67
|
+
found.push(def.keyType, def.valueType);
|
|
68
|
+
break;
|
|
69
|
+
case "tuple":
|
|
70
|
+
found.push(...(def.items as unknown[]), def.rest);
|
|
71
|
+
break;
|
|
72
|
+
case "intersection":
|
|
73
|
+
found.push(def.left, def.right);
|
|
74
|
+
break;
|
|
75
|
+
case "lazy":
|
|
76
|
+
found.push((def.getter as () => unknown)());
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
return found.filter((child): child is z.ZodType => child !== undefined);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function containsDate(schema: z.ZodType, seen: Set<z.ZodType>): boolean {
|
|
83
|
+
if (seen.has(schema)) return false;
|
|
84
|
+
seen.add(schema);
|
|
85
|
+
if (schema._zod.def.type === "date") return true;
|
|
86
|
+
return children(schema).some((child) => containsDate(child, seen));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const RFC_3339 =
|
|
90
|
+
/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
|
|
91
|
+
|
|
92
|
+
function parseDate(text: string): Date | undefined {
|
|
93
|
+
if (!RFC_3339.test(text)) return undefined;
|
|
94
|
+
const date = new Date(text.toUpperCase());
|
|
95
|
+
return Number.isNaN(date.getTime()) ? undefined : date;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
99
|
+
if (typeof value !== "object" || value === null) return false;
|
|
100
|
+
const prototype = Object.getPrototypeOf(value);
|
|
101
|
+
return prototype === Object.prototype || prototype === null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// How to convert a value of `schema`, or undefined when no date lies below it.
|
|
105
|
+
// A date under a container the walk cannot enter would reach the procedure as
|
|
106
|
+
// the string it arrived as, so it is refused when the tool is built.
|
|
107
|
+
function datePlan(schema: z.ZodType): Convert | undefined {
|
|
108
|
+
const type = schema._zod.def.type;
|
|
109
|
+
switch (type) {
|
|
110
|
+
case "date":
|
|
111
|
+
return (value) =>
|
|
112
|
+
typeof value === "string" ? (parseDate(value) ?? value) : value;
|
|
113
|
+
case "object": {
|
|
114
|
+
const plans: Array<[string, Convert]> = [];
|
|
115
|
+
for (const [key, child] of Object.entries(
|
|
116
|
+
(schema as z.ZodObject).shape as Record<string, z.ZodType>,
|
|
117
|
+
)) {
|
|
118
|
+
const plan = datePlan(child);
|
|
119
|
+
if (plan) plans.push([key, plan]);
|
|
120
|
+
}
|
|
121
|
+
if (plans.length === 0) return undefined;
|
|
122
|
+
return (value) => {
|
|
123
|
+
if (!isPlainObject(value)) return value;
|
|
124
|
+
const out = { ...value };
|
|
125
|
+
for (const [key, plan] of plans) {
|
|
126
|
+
if (key in out) out[key] = plan(out[key]);
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
case "array": {
|
|
132
|
+
const plan = datePlan((schema as z.ZodArray).element as z.ZodType);
|
|
133
|
+
if (!plan) return undefined;
|
|
134
|
+
return (value) => (Array.isArray(value) ? value.map(plan) : value);
|
|
135
|
+
}
|
|
136
|
+
case "optional":
|
|
137
|
+
case "nullable":
|
|
138
|
+
case "default":
|
|
139
|
+
case "prefault":
|
|
140
|
+
case "nonoptional":
|
|
141
|
+
case "readonly":
|
|
142
|
+
case "catch":
|
|
143
|
+
case "pipe": {
|
|
144
|
+
const [inner] = children(schema);
|
|
145
|
+
return inner ? datePlan(inner) : undefined;
|
|
146
|
+
}
|
|
147
|
+
case "union": {
|
|
148
|
+
const plans = children(schema)
|
|
149
|
+
.map(datePlan)
|
|
150
|
+
.filter((plan): plan is Convert => plan !== undefined);
|
|
151
|
+
if (plans.length === 0) return undefined;
|
|
152
|
+
return (value) => plans.reduce((acc, plan) => plan(acc), value);
|
|
153
|
+
}
|
|
154
|
+
default:
|
|
155
|
+
if (containsDate(schema, new Set())) {
|
|
156
|
+
throw new Error(
|
|
157
|
+
`a date inside a ${type} cannot be converted from its string`,
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function resolvePath(routes: unknown, path: string): unknown {
|
|
165
|
+
let node = routes;
|
|
166
|
+
for (const segment of path.split(".")) {
|
|
167
|
+
if (
|
|
168
|
+
(typeof node !== "object" && typeof node !== "function") ||
|
|
169
|
+
node === null ||
|
|
170
|
+
!Object.hasOwn(node, segment)
|
|
171
|
+
) {
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
node = (node as Record<string, unknown>)[segment];
|
|
175
|
+
}
|
|
176
|
+
return node;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Resolves every tool of `definition` against the consumer's routes, in the
|
|
180
|
+
// definition's order. A tool the endpoint could not serve throws here, naming
|
|
181
|
+
// the tool, so a worker never boots with it.
|
|
182
|
+
export function buildMcpTools(
|
|
183
|
+
routes: Record<string, unknown> | undefined,
|
|
184
|
+
definition: McpDefinition,
|
|
185
|
+
): McpTool[] {
|
|
186
|
+
const tools: McpTool[] = [];
|
|
187
|
+
for (const [name, description] of Object.entries(definition.tools)) {
|
|
188
|
+
const refuse = (reason: string) =>
|
|
189
|
+
new Error(`createWorker: MCP tool "${name}" ${reason}.`);
|
|
190
|
+
if (!TOOL_NAME.test(name)) {
|
|
191
|
+
throw refuse(
|
|
192
|
+
"is not a valid name: MCP names hold 1 to 128 letters, digits, `_`, `-` and `.`",
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
if (typeof description !== "string") {
|
|
196
|
+
throw refuse("has no description");
|
|
197
|
+
}
|
|
198
|
+
const procedure = resolvePath(routes, name);
|
|
199
|
+
if (!isProcedure(procedure))
|
|
200
|
+
throw refuse("names no procedure in the routes");
|
|
201
|
+
const def = procedure["~orpc"];
|
|
202
|
+
const schema = def.inputSchema as z.ZodType | undefined;
|
|
203
|
+
if (schema !== undefined && !(schema instanceof z.ZodType)) {
|
|
204
|
+
throw refuse("has an input that is not a zod schema");
|
|
205
|
+
}
|
|
206
|
+
let inputSchema: Tool["inputSchema"];
|
|
207
|
+
let convert: Convert | undefined;
|
|
208
|
+
try {
|
|
209
|
+
inputSchema = inputJsonSchema(schema) as Tool["inputSchema"];
|
|
210
|
+
convert = schema && datePlan(schema);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
213
|
+
throw refuse(`cannot be served: ${reason}`);
|
|
214
|
+
}
|
|
215
|
+
tools.push({
|
|
216
|
+
name,
|
|
217
|
+
description,
|
|
218
|
+
inputSchema,
|
|
219
|
+
readOnly: (def.meta as { kind?: string } | undefined)?.kind === "query",
|
|
220
|
+
procedure,
|
|
221
|
+
convert: convert ?? ((args) => args),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return tools;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
interface CallExtra {
|
|
228
|
+
// What the procedure runs with: the Slotform context, the pinned tenancy and
|
|
229
|
+
// the verified caller.
|
|
230
|
+
context: Record<string, unknown>;
|
|
231
|
+
organizationId: string;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function toResult(value: unknown, isError = false): CallToolResult {
|
|
235
|
+
const parsed: unknown = JSON.parse(JSON.stringify(value ?? null));
|
|
236
|
+
const structured = isPlainObject(parsed) ? parsed : { result: parsed };
|
|
237
|
+
return {
|
|
238
|
+
content: [{ type: "text", text: JSON.stringify(structured) }],
|
|
239
|
+
structuredContent: structured,
|
|
240
|
+
...(isError ? { isError: true as const } : {}),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function runTool(
|
|
245
|
+
tool: McpTool,
|
|
246
|
+
args: unknown,
|
|
247
|
+
context: Record<string, unknown>,
|
|
248
|
+
): Promise<CallToolResult> {
|
|
249
|
+
try {
|
|
250
|
+
const output = await call(tool.procedure, tool.convert(args ?? {}), {
|
|
251
|
+
context,
|
|
252
|
+
});
|
|
253
|
+
return toResult(output);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (error instanceof ORPCError) {
|
|
256
|
+
try {
|
|
257
|
+
return toResult(
|
|
258
|
+
{ code: error.code, message: error.message, data: error.data },
|
|
259
|
+
true,
|
|
260
|
+
);
|
|
261
|
+
} catch {
|
|
262
|
+
// Error data JSON cannot hold: masked like any other failure.
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
console.error(`[mcp] tool "${tool.name}" failed:`, error);
|
|
266
|
+
return toResult(INTERNAL, true);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
type Sdk = typeof import("@modelcontextprotocol/server");
|
|
271
|
+
|
|
272
|
+
interface McpEndpoint {
|
|
273
|
+
fetch(
|
|
274
|
+
request: Request,
|
|
275
|
+
options: { parsedBody: unknown; authInfo: AuthInfo },
|
|
276
|
+
): Promise<Response>;
|
|
277
|
+
// Reads a request body up to the 4 MiB bound; null beyond it.
|
|
278
|
+
readBody(request: Request): Promise<string | null>;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function createMcpEndpoint(options: {
|
|
282
|
+
tools: McpTool[];
|
|
283
|
+
instructions: string;
|
|
284
|
+
name: string;
|
|
285
|
+
}): McpEndpoint {
|
|
286
|
+
const listed = options.tools.map(
|
|
287
|
+
(tool): Tool => ({
|
|
288
|
+
name: tool.name,
|
|
289
|
+
description: tool.description,
|
|
290
|
+
inputSchema: tool.inputSchema,
|
|
291
|
+
...(tool.readOnly ? { annotations: { readOnlyHint: true } } : {}),
|
|
292
|
+
}),
|
|
293
|
+
);
|
|
294
|
+
const byName = new Map(options.tools.map((tool) => [tool.name, tool]));
|
|
295
|
+
|
|
296
|
+
let sdk: Promise<Sdk> | undefined;
|
|
297
|
+
const loadSdk = (): Promise<Sdk> => {
|
|
298
|
+
sdk ??= import("@modelcontextprotocol/server").catch((error) => {
|
|
299
|
+
sdk = undefined;
|
|
300
|
+
throw error;
|
|
301
|
+
});
|
|
302
|
+
return sdk;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
let handler: Promise<McpHttpHandler> | undefined;
|
|
306
|
+
const loadHandler = (): Promise<McpHttpHandler> => {
|
|
307
|
+
handler ??= build().catch((error) => {
|
|
308
|
+
handler = undefined;
|
|
309
|
+
throw error;
|
|
310
|
+
});
|
|
311
|
+
return handler;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
// One handler per worker, one server per request: nothing is held between
|
|
315
|
+
// calls, so the 2025-era leg needs no session store.
|
|
316
|
+
async function build(): Promise<McpHttpHandler> {
|
|
317
|
+
const { createMcpHandler, Server, ProtocolError, ProtocolErrorCode } =
|
|
318
|
+
await loadSdk();
|
|
319
|
+
const factory = (request: McpRequestContext) => {
|
|
320
|
+
const extra = request.authInfo?.extra as CallExtra | undefined;
|
|
321
|
+
if (!extra) {
|
|
322
|
+
throw new Error("mcp: the request reached the server unauthenticated");
|
|
323
|
+
}
|
|
324
|
+
const server = new Server(
|
|
325
|
+
{ name: options.name, version: SERVER_VERSION },
|
|
326
|
+
{
|
|
327
|
+
capabilities: { tools: {} },
|
|
328
|
+
instructions: `${options.instructions}\n\nThis connection acts in the organization with id ${extra.organizationId}`,
|
|
329
|
+
},
|
|
330
|
+
);
|
|
331
|
+
server.setRequestHandler("tools/list", () => ({ tools: listed }));
|
|
332
|
+
server.setRequestHandler("tools/call", ({ params }) => {
|
|
333
|
+
const tool = byName.get(params.name);
|
|
334
|
+
if (!tool) {
|
|
335
|
+
throw new ProtocolError(
|
|
336
|
+
ProtocolErrorCode.InvalidParams,
|
|
337
|
+
`Unknown tool: ${params.name}`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return runTool(tool, params.arguments, extra.context);
|
|
341
|
+
});
|
|
342
|
+
return server;
|
|
343
|
+
};
|
|
344
|
+
return createMcpHandler(factory, {
|
|
345
|
+
legacy: "stateless",
|
|
346
|
+
// No need names `subscriptions/listen`, which a Worker would hold open.
|
|
347
|
+
maxSubscriptions: 0,
|
|
348
|
+
onerror: (error) => console.error("[mcp] SDK error:", error),
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return {
|
|
353
|
+
async fetch(request, init) {
|
|
354
|
+
return (await loadHandler()).fetch(request, init);
|
|
355
|
+
},
|
|
356
|
+
async readBody(request) {
|
|
357
|
+
const { readRequestBody } = await loadSdk();
|
|
358
|
+
const read = await readRequestBody(request, MAX_BODY_BYTES);
|
|
359
|
+
return read.tooLarge ? null : read.text;
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
interface VerifiedCaller {
|
|
365
|
+
user: unknown;
|
|
366
|
+
session: { expiresAt: Date };
|
|
367
|
+
grant: { clientId: string; organizationId: string; scopes: string[] };
|
|
368
|
+
tenancy: unknown;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function jsonRpcError(code: number, message: string, status: number): Response {
|
|
372
|
+
return Response.json(
|
|
373
|
+
{ jsonrpc: "2.0", error: { code, message }, id: null },
|
|
374
|
+
{ status },
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function createMcpRoute(endpoint: McpEndpoint) {
|
|
379
|
+
return async (
|
|
380
|
+
c: Context,
|
|
381
|
+
ctx: Record<string, unknown>,
|
|
382
|
+
): Promise<Response> => {
|
|
383
|
+
if (isForbiddenOrigin(c)) {
|
|
384
|
+
return c.json({ code: "FORBIDDEN" }, 403);
|
|
385
|
+
}
|
|
386
|
+
const oauth = ctx.oauth as
|
|
387
|
+
| {
|
|
388
|
+
verify(request: Request): Promise<VerifiedCaller | Response>;
|
|
389
|
+
}
|
|
390
|
+
| undefined;
|
|
391
|
+
if (!oauth) {
|
|
392
|
+
throw new Error(
|
|
393
|
+
"mcp: the request context has no `oauth`; the MCP endpoint needs auth({ mcp: true }).",
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
const request = c.req.raw;
|
|
397
|
+
const verified = await oauth.verify(request);
|
|
398
|
+
if (verified instanceof Response) {
|
|
399
|
+
// A forged `kid` costs a key refetch, so a refused token draws the
|
|
400
|
+
// per-IP budget. An accepted token never does: hosted clients share
|
|
401
|
+
// egress, and `verify` limits per grant.
|
|
402
|
+
if (verified.status === 401 && (await ipLimited(c, ctx))) {
|
|
403
|
+
return c.json({ code: "TOO_MANY_REQUESTS" }, 429);
|
|
404
|
+
}
|
|
405
|
+
return verified;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const text = await endpoint.readBody(request);
|
|
409
|
+
if (text === null) {
|
|
410
|
+
return jsonRpcError(-32000, "Request body too large", 413);
|
|
411
|
+
}
|
|
412
|
+
let parsedBody: unknown;
|
|
413
|
+
try {
|
|
414
|
+
parsedBody = JSON.parse(text);
|
|
415
|
+
} catch {
|
|
416
|
+
return jsonRpcError(
|
|
417
|
+
-32700,
|
|
418
|
+
"Parse error: the body is not valid JSON",
|
|
419
|
+
400,
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
// One POST is one call, so the grant's limit counts calls.
|
|
423
|
+
if (Array.isArray(parsedBody)) {
|
|
424
|
+
return jsonRpcError(
|
|
425
|
+
-32600,
|
|
426
|
+
"Invalid request: batches are not served",
|
|
427
|
+
400,
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const reqHeaders = new Headers(request.headers);
|
|
432
|
+
reqHeaders.delete("cookie");
|
|
433
|
+
reqHeaders.delete("authorization");
|
|
434
|
+
const env = ctx.env as Record<string, unknown> | undefined;
|
|
435
|
+
const appUrl = env?.APP_URL;
|
|
436
|
+
const token = request.headers.get("authorization")?.split(/\s+/)[1] ?? "";
|
|
437
|
+
const authInfo: AuthInfo = {
|
|
438
|
+
token,
|
|
439
|
+
clientId: verified.grant.clientId,
|
|
440
|
+
scopes: verified.grant.scopes,
|
|
441
|
+
expiresAt: Math.floor(verified.session.expiresAt.getTime() / 1000),
|
|
442
|
+
...(typeof appUrl === "string"
|
|
443
|
+
? { resource: new URL(`${appUrl.replace(/\/+$/, "")}${MCP_PATH}`) }
|
|
444
|
+
: {}),
|
|
445
|
+
extra: {
|
|
446
|
+
context: {
|
|
447
|
+
...ctx,
|
|
448
|
+
tenancy: verified.tenancy,
|
|
449
|
+
_caller: { user: verified.user, session: verified.session },
|
|
450
|
+
reqHeaders,
|
|
451
|
+
// The request without its body or credentials, so a procedure that
|
|
452
|
+
// forwards headers to Better Auth finds no session.
|
|
453
|
+
httpRequest: new Request(request.url, {
|
|
454
|
+
method: request.method,
|
|
455
|
+
headers: reqHeaders,
|
|
456
|
+
}),
|
|
457
|
+
resHeaders: new Headers(),
|
|
458
|
+
},
|
|
459
|
+
organizationId: verified.grant.organizationId,
|
|
460
|
+
} satisfies CallExtra,
|
|
461
|
+
};
|
|
462
|
+
return endpoint.fetch(
|
|
463
|
+
new Request(request.url, {
|
|
464
|
+
method: request.method,
|
|
465
|
+
headers: request.headers,
|
|
466
|
+
}),
|
|
467
|
+
{ parsedBody, authInfo },
|
|
468
|
+
);
|
|
469
|
+
};
|
|
470
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from "hono";
|
|
2
|
+
|
|
3
|
+
// Request log without query strings: docs/architecture/plugins/api.md, "Logging".
|
|
4
|
+
|
|
5
|
+
function formatDuration(ms: number): string {
|
|
6
|
+
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function pathnameOf(url: string): string {
|
|
10
|
+
const end = url.search(/[?#]/);
|
|
11
|
+
const head = end === -1 ? url : url.slice(0, end);
|
|
12
|
+
const scheme = head.indexOf("://");
|
|
13
|
+
if (scheme === -1) return head;
|
|
14
|
+
const path = head.indexOf("/", scheme + 3);
|
|
15
|
+
return path === -1 ? "/" : head.slice(path);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function formatRequestLog(line: {
|
|
19
|
+
method: string;
|
|
20
|
+
url: string;
|
|
21
|
+
status?: number;
|
|
22
|
+
ms?: number;
|
|
23
|
+
}): string {
|
|
24
|
+
const path = pathnameOf(line.url);
|
|
25
|
+
if (line.status === undefined || line.ms === undefined) {
|
|
26
|
+
return `<-- ${line.method} ${path}`;
|
|
27
|
+
}
|
|
28
|
+
return `--> ${line.method} ${path} ${line.status} ${formatDuration(line.ms)}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// `print` is the test's seam: the worker prints through the console.
|
|
32
|
+
export function requestLogger(
|
|
33
|
+
print: (line: string) => void = console.log,
|
|
34
|
+
): MiddlewareHandler {
|
|
35
|
+
return async (c, next) => {
|
|
36
|
+
const { method } = c.req;
|
|
37
|
+
const url = c.req.url;
|
|
38
|
+
print(formatRequestLog({ method, url }));
|
|
39
|
+
const start = Date.now();
|
|
40
|
+
await next();
|
|
41
|
+
print(
|
|
42
|
+
formatRequestLog({
|
|
43
|
+
method,
|
|
44
|
+
url,
|
|
45
|
+
status: c.res.status,
|
|
46
|
+
ms: Date.now() - start,
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
}
|