@graxia/mcp 0.0.0-stage → 0.1.1
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 +169 -2
- package/dist/auth/bearer.d.ts +17 -0
- package/dist/auth/bearer.d.ts.map +1 -0
- package/dist/auth/metadata.d.ts +8 -0
- package/dist/auth/metadata.d.ts.map +1 -0
- package/dist/auth/principal.d.ts +17 -0
- package/dist/auth/principal.d.ts.map +1 -0
- package/dist/auth/resolve.d.ts +4 -0
- package/dist/auth/resolve.d.ts.map +1 -0
- package/dist/auth/scopes.d.ts +14 -0
- package/dist/auth/scopes.d.ts.map +1 -0
- package/dist/auth/types.d.ts +70 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/body.d.ts +6 -0
- package/dist/body.d.ts.map +1 -0
- package/dist/calls.d.ts +14 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/codes.d.ts +21 -0
- package/dist/codes.d.ts.map +1 -0
- package/dist/context.d.ts +20 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/cors.d.ts +7 -0
- package/dist/cors.d.ts.map +1 -0
- package/dist/create.d.ts +29 -0
- package/dist/create.d.ts.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1533 -0
- package/dist/index.js.map +45 -0
- package/dist/operations/build.d.ts +10 -0
- package/dist/operations/build.d.ts.map +1 -0
- package/dist/operations/constraint.d.ts +16 -0
- package/dist/operations/constraint.d.ts.map +1 -0
- package/dist/operations/documents.d.ts +13 -0
- package/dist/operations/documents.d.ts.map +1 -0
- package/dist/operations/input-schema.d.ts +12 -0
- package/dist/operations/input-schema.d.ts.map +1 -0
- package/dist/operations/input-type.d.ts +18 -0
- package/dist/operations/input-type.d.ts.map +1 -0
- package/dist/operations/naming.d.ts +5 -0
- package/dist/operations/naming.d.ts.map +1 -0
- package/dist/operations/output-schema.d.ts +11 -0
- package/dist/operations/output-schema.d.ts.map +1 -0
- package/dist/operations/problems.d.ts +27 -0
- package/dist/operations/problems.d.ts.map +1 -0
- package/dist/operations/register.d.ts +20 -0
- package/dist/operations/register.d.ts.map +1 -0
- package/dist/operations/types.d.ts +49 -0
- package/dist/operations/types.d.ts.map +1 -0
- package/dist/operations/variable-usage.d.ts +16 -0
- package/dist/operations/variable-usage.d.ts.map +1 -0
- package/dist/operations/visible.d.ts +10 -0
- package/dist/operations/visible.d.ts.map +1 -0
- package/dist/options.d.ts +116 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/origin-options.d.ts +9 -0
- package/dist/origin-options.d.ts.map +1 -0
- package/dist/origin.d.ts +18 -0
- package/dist/origin.d.ts.map +1 -0
- package/dist/pipeline.d.ts +16 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/refusal.d.ts +4 -0
- package/dist/refusal.d.ts.map +1 -0
- package/dist/server.d.ts +28 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/tools/execute.d.ts +32 -0
- package/dist/tools/execute.d.ts.map +1 -0
- package/dist/tools/guard.d.ts +8 -0
- package/dist/tools/guard.d.ts.map +1 -0
- package/dist/tools/index.d.ts +17 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/operation.d.ts +35 -0
- package/dist/tools/operation.d.ts.map +1 -0
- package/dist/tools/result.d.ts +13 -0
- package/dist/tools/result.d.ts.map +1 -0
- package/dist/tools/schema.d.ts +319 -0
- package/dist/tools/schema.d.ts.map +1 -0
- package/dist/tools/strict.d.ts +12 -0
- package/dist/tools/strict.d.ts.map +1 -0
- package/dist/toolset.d.ts +30 -0
- package/dist/toolset.d.ts.map +1 -0
- package/dist/view-cache.d.ts +13 -0
- package/dist/view-cache.d.ts.map +1 -0
- package/dist/view.d.ts +16 -0
- package/dist/view.d.ts.map +1 -0
- package/docs/README.md +9 -0
- package/docs/guide/auth.md +247 -0
- package/docs/guide/getting-started.md +82 -0
- package/docs/guide/operations.md +221 -0
- package/docs/guide/security.md +122 -0
- package/docs/guide/tools.md +102 -0
- package/docs/roadmap.md +32 -0
- package/docs/troubleshooting-auth.md +101 -0
- package/docs/troubleshooting.md +205 -0
- package/package.json +71 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,1533 @@
|
|
|
1
|
+
// src/auth/principal.ts
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
var storage = new AsyncLocalStorage;
|
|
4
|
+
function runAs(info, fn) {
|
|
5
|
+
return storage.run(info, fn);
|
|
6
|
+
}
|
|
7
|
+
function mcpAuth() {
|
|
8
|
+
return storage.getStore();
|
|
9
|
+
}
|
|
10
|
+
// src/create.ts
|
|
11
|
+
import { createMcpHandler } from "@modelcontextprotocol/server";
|
|
12
|
+
|
|
13
|
+
// src/refusal.ts
|
|
14
|
+
function refusal(status, message, fix, headers = {}, code) {
|
|
15
|
+
return Response.json({
|
|
16
|
+
jsonrpc: "2.0",
|
|
17
|
+
error: {
|
|
18
|
+
code: -32000,
|
|
19
|
+
message,
|
|
20
|
+
data: code === undefined ? { fix } : { code, fix }
|
|
21
|
+
},
|
|
22
|
+
id: null
|
|
23
|
+
}, { status, headers });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/auth/bearer.ts
|
|
27
|
+
function challenge(auth, params) {
|
|
28
|
+
const parts = [];
|
|
29
|
+
if (params.error)
|
|
30
|
+
parts.push(`error="${params.error}"`);
|
|
31
|
+
if (params.description)
|
|
32
|
+
parts.push(`error_description="${params.description}"`);
|
|
33
|
+
parts.push(`resource_metadata="${auth.metadataUrl}"`);
|
|
34
|
+
if (params.scope)
|
|
35
|
+
parts.push(`scope="${params.scope}"`);
|
|
36
|
+
return `Bearer ${parts.join(", ")}`;
|
|
37
|
+
}
|
|
38
|
+
var bearerOf = (request) => {
|
|
39
|
+
const match = /^Bearer\s+(\S+)\s*$/i.exec(request.headers.get("authorization") ?? "");
|
|
40
|
+
return match?.[1];
|
|
41
|
+
};
|
|
42
|
+
var sameResource = (a, b) => {
|
|
43
|
+
const clean = (s) => s.replace(/#.*$/, "").replace(/\/$/, "");
|
|
44
|
+
return clean(a) === clean(b);
|
|
45
|
+
};
|
|
46
|
+
var unauthorized = (auth, description, fix) => refusal(401, `Unauthorized: ${description}.`, fix, {
|
|
47
|
+
"www-authenticate": challenge(auth, {
|
|
48
|
+
error: "invalid_token",
|
|
49
|
+
description
|
|
50
|
+
})
|
|
51
|
+
}, "MCP_UNAUTHORIZED");
|
|
52
|
+
var unavailable = () => refusal(503, "The access token could not be verified: the token verifier failed.", "Retry in a few seconds with the same token. If it persists, the server owner should read the error onError received. A verifier that throws for an invalid token must resolve undefined instead.", { "retry-after": "5" });
|
|
53
|
+
var MAX_EXPIRES_AT = 100000000000;
|
|
54
|
+
function refusalOf(info, auth, onError) {
|
|
55
|
+
const { resource } = auth.options;
|
|
56
|
+
const renew = `Get a new access token from the authorization server (see ${auth.metadataUrl}) and retry.`;
|
|
57
|
+
const owner = (what, fix) => {
|
|
58
|
+
onError(new Error(`createMcp: ${what}. Fix: ${fix}`));
|
|
59
|
+
return "Retry later; the server owner has to correct its token verifier (the error went to onError).";
|
|
60
|
+
};
|
|
61
|
+
if (!Array.isArray(info.scopes))
|
|
62
|
+
return unauthorized(auth, "the verifier returned no scopes", owner("verifyToken must return scopes", "return { scopes: [...] }, the list of scopes the token carries (an empty list for none)."));
|
|
63
|
+
const { expiresAt } = info;
|
|
64
|
+
if (expiresAt !== undefined) {
|
|
65
|
+
if (!Number.isFinite(expiresAt) || expiresAt > MAX_EXPIRES_AT)
|
|
66
|
+
return unauthorized(auth, "the verifier returned an unusable expiry (expiresAt is in seconds)", owner(`verifyToken returned expiresAt ${String(expiresAt)}, and expiresAt is in seconds since the epoch`, "return the exp claim as is, or Math.floor(date.getTime() / 1000); leave it out when the token has no expiry."));
|
|
67
|
+
if (expiresAt <= Date.now() / 1000)
|
|
68
|
+
return unauthorized(auth, "the access token has expired", renew);
|
|
69
|
+
}
|
|
70
|
+
if (auth.options.audience !== "verifier") {
|
|
71
|
+
const forResource = `Get an access token issued for ${resource} (the "resource" parameter of the authorization and token requests, RFC 8707) and retry.`;
|
|
72
|
+
if (info.audience === undefined)
|
|
73
|
+
return unauthorized(auth, "the access token carries no audience", `${forResource} Server owner: return audience from verifyToken, or set auth.audience to 'verifier' when the verifier checks it itself.`);
|
|
74
|
+
const audiences = typeof info.audience === "string" ? [info.audience] : info.audience;
|
|
75
|
+
if (!audiences.some((a) => sameResource(a, resource)))
|
|
76
|
+
return unauthorized(auth, "the access token was issued for another resource", forResource);
|
|
77
|
+
}
|
|
78
|
+
if (!info.scopes.includes(auth.read))
|
|
79
|
+
return insufficient(auth, [auth.read], `the token lacks ${auth.read}`);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
async function authenticate(request, auth, onError) {
|
|
83
|
+
if (new URL(request.url).searchParams.has("access_token"))
|
|
84
|
+
return refusal(400, "The access token is in the query string.", "Send the token in the header Authorization: Bearer <token>; a token in a URL is refused.", { "www-authenticate": challenge(auth, { error: "invalid_request" }) }, "MCP_TOKEN_IN_URL");
|
|
85
|
+
const token = bearerOf(request);
|
|
86
|
+
if (token === undefined)
|
|
87
|
+
return refusal(401, "Unauthorized: no bearer token.", `Send Authorization: Bearer <token>. Fetch the authorization server from ${auth.metadataUrl}, get a token with the scope ${auth.read}, and retry.`, { "www-authenticate": challenge(auth, { scope: auth.read }) }, "MCP_UNAUTHORIZED");
|
|
88
|
+
let verified;
|
|
89
|
+
try {
|
|
90
|
+
verified = await auth.options.verifyToken(token, request);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
onError(error);
|
|
93
|
+
return unavailable();
|
|
94
|
+
}
|
|
95
|
+
if (verified instanceof Response)
|
|
96
|
+
return verified;
|
|
97
|
+
if (verified === undefined || verified === null)
|
|
98
|
+
return unauthorized(auth, "the access token is invalid", `Get a new access token from the authorization server (see ${auth.metadataUrl}) and retry.`);
|
|
99
|
+
return refusalOf(verified, auth, onError) ?? verified;
|
|
100
|
+
}
|
|
101
|
+
function insufficient(auth, scopes, description) {
|
|
102
|
+
const scope = scopes.join(" ");
|
|
103
|
+
return refusal(403, `Forbidden: ${description}.`, `Ask the authorization server for a token with the scope${scopes.length > 1 ? "s" : ""} "${scope}" (see ${auth.metadataUrl}), then retry.`, {
|
|
104
|
+
"www-authenticate": challenge(auth, {
|
|
105
|
+
error: "insufficient_scope",
|
|
106
|
+
description,
|
|
107
|
+
scope
|
|
108
|
+
})
|
|
109
|
+
}, "MCP_INSUFFICIENT_SCOPE");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/auth/metadata.ts
|
|
113
|
+
var CORS = { "access-control-allow-origin": "*" };
|
|
114
|
+
function metadataHandler(auth, mutations) {
|
|
115
|
+
if (auth === undefined)
|
|
116
|
+
return () => new Response(null, { status: 404 });
|
|
117
|
+
const { options } = auth;
|
|
118
|
+
const body = JSON.stringify({
|
|
119
|
+
resource: options.resource,
|
|
120
|
+
authorization_servers: options.authorizationServers,
|
|
121
|
+
scopes_supported: mutations ? [auth.read, auth.write] : [auth.read],
|
|
122
|
+
bearer_methods_supported: ["header"],
|
|
123
|
+
...options.resourceName !== undefined && {
|
|
124
|
+
resource_name: options.resourceName
|
|
125
|
+
},
|
|
126
|
+
...options.documentation !== undefined && {
|
|
127
|
+
resource_documentation: options.documentation
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
return (request) => {
|
|
131
|
+
if (request.method === "OPTIONS")
|
|
132
|
+
return new Response(null, {
|
|
133
|
+
status: 204,
|
|
134
|
+
headers: {
|
|
135
|
+
...CORS,
|
|
136
|
+
"access-control-allow-methods": "GET",
|
|
137
|
+
"access-control-max-age": "3600"
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
141
|
+
return new Response(null, {
|
|
142
|
+
status: 405,
|
|
143
|
+
headers: { ...CORS, allow: "GET, HEAD, OPTIONS" }
|
|
144
|
+
});
|
|
145
|
+
return new Response(request.method === "HEAD" ? null : body, {
|
|
146
|
+
headers: {
|
|
147
|
+
...CORS,
|
|
148
|
+
"content-type": "application/json",
|
|
149
|
+
"cache-control": "max-age=3600"
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/auth/resolve.ts
|
|
156
|
+
import { GraxiaConfigError } from "@graxia/core";
|
|
157
|
+
import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/server";
|
|
158
|
+
function resolveAuth(options) {
|
|
159
|
+
let url;
|
|
160
|
+
try {
|
|
161
|
+
url = new URL(options.resource);
|
|
162
|
+
} catch {
|
|
163
|
+
throw new GraxiaConfigError(`createMcp: auth.resource must be an absolute URL (got "${options.resource}"). Fix: pass the public URL of the MCP endpoint, e.g. https://api.example.com/mcp.`);
|
|
164
|
+
}
|
|
165
|
+
if (url.hash !== "" || url.search !== "" || /[?#]$/.test(options.resource))
|
|
166
|
+
throw new GraxiaConfigError(`createMcp: auth.resource must have no query and no fragment (got "${options.resource}"). Fix: pass the URL of the MCP endpoint alone, e.g. ${url.origin}${url.pathname}.`);
|
|
167
|
+
if (options.authorizationServers.length === 0)
|
|
168
|
+
throw new GraxiaConfigError("createMcp: auth.authorizationServers is empty. Fix: list the issuer URL of the authorization server that issues the tokens.");
|
|
169
|
+
for (const server of options.authorizationServers)
|
|
170
|
+
if (!URL.canParse(server))
|
|
171
|
+
throw new GraxiaConfigError(`createMcp: auth.authorizationServers must hold absolute URLs (got "${server}"). Fix: pass the issuer URL of the authorization server, e.g. https://auth.example.com.`);
|
|
172
|
+
const metadataUrl = getOAuthProtectedResourceMetadataUrl(url);
|
|
173
|
+
return {
|
|
174
|
+
options,
|
|
175
|
+
read: options.scopes?.read ?? "mcp:read",
|
|
176
|
+
write: options.scopes?.write ?? "mcp:write",
|
|
177
|
+
metadataUrl,
|
|
178
|
+
metadataPath: new URL(metadataUrl).pathname
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/auth/scopes.ts
|
|
183
|
+
var canWrite = (auth, info) => info.scopes.includes(auth.write);
|
|
184
|
+
async function writeStepUp(auth, info, called, writes) {
|
|
185
|
+
if (canWrite(auth, info))
|
|
186
|
+
return;
|
|
187
|
+
for (const name of called)
|
|
188
|
+
if (await writes(name))
|
|
189
|
+
return insufficient(auth, [auth.read, auth.write], `${name} needs the scope ${auth.write}`);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/calls.ts
|
|
194
|
+
async function toolCallsOf(request) {
|
|
195
|
+
let body;
|
|
196
|
+
try {
|
|
197
|
+
body = JSON.parse(await request.clone().text());
|
|
198
|
+
} catch {
|
|
199
|
+
return { list: false, called: [] };
|
|
200
|
+
}
|
|
201
|
+
let list = false;
|
|
202
|
+
const called = [];
|
|
203
|
+
for (const message of Array.isArray(body) ? body : [body]) {
|
|
204
|
+
if (typeof message !== "object" || message === null)
|
|
205
|
+
continue;
|
|
206
|
+
const { method, params } = message;
|
|
207
|
+
if (method === "tools/list")
|
|
208
|
+
list = true;
|
|
209
|
+
if (method === "tools/call" && typeof params?.name === "string")
|
|
210
|
+
called.push(params.name);
|
|
211
|
+
}
|
|
212
|
+
return { list, called };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/context.ts
|
|
216
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
217
|
+
function createContextCarrier() {
|
|
218
|
+
const storage = new AsyncLocalStorage2;
|
|
219
|
+
return {
|
|
220
|
+
run: (state, fn) => storage.run(state, fn),
|
|
221
|
+
current() {
|
|
222
|
+
const store = storage.getStore();
|
|
223
|
+
if (store === undefined)
|
|
224
|
+
throw new Error("createMcp: no serverContext for this request; the MCP handler ran outside fetch.");
|
|
225
|
+
return store;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/cors.ts
|
|
231
|
+
var ALLOW_HEADERS = "content-type, authorization, mcp-protocol-version, mcp-session-id, mcp-method, mcp-name, last-event-id, accept";
|
|
232
|
+
function corsOrigin(request, allowed) {
|
|
233
|
+
const origin = request.headers.get("origin");
|
|
234
|
+
return origin !== null && allowed.includes(origin) ? origin : undefined;
|
|
235
|
+
}
|
|
236
|
+
function preflight(origin, requested) {
|
|
237
|
+
return new Response(null, {
|
|
238
|
+
status: 204,
|
|
239
|
+
headers: {
|
|
240
|
+
"access-control-allow-origin": origin,
|
|
241
|
+
"access-control-allow-methods": "POST",
|
|
242
|
+
"access-control-allow-headers": requested ? `${ALLOW_HEADERS}, ${requested}` : ALLOW_HEADERS,
|
|
243
|
+
"access-control-max-age": "600",
|
|
244
|
+
vary: "Origin"
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function withCors(response, origin) {
|
|
249
|
+
if (origin === undefined || response.headers.has("access-control-allow-origin"))
|
|
250
|
+
return response;
|
|
251
|
+
const headers = new Headers(response.headers);
|
|
252
|
+
headers.set("access-control-allow-origin", origin);
|
|
253
|
+
headers.set("access-control-expose-headers", "mcp-protocol-version, www-authenticate");
|
|
254
|
+
headers.append("vary", "Origin");
|
|
255
|
+
return new Response(response.body, {
|
|
256
|
+
status: response.status,
|
|
257
|
+
statusText: response.statusText,
|
|
258
|
+
headers
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/origin.ts
|
|
263
|
+
import {
|
|
264
|
+
localhostAllowedHostnames,
|
|
265
|
+
validateHostHeader
|
|
266
|
+
} from "@modelcontextprotocol/server";
|
|
267
|
+
var defaultHosts = () => localhostAllowedHostnames();
|
|
268
|
+
function checkOrigin(request, policy) {
|
|
269
|
+
const origin = request.headers.get("origin");
|
|
270
|
+
if (origin === null || policy.allowedOrigins.includes(origin))
|
|
271
|
+
return;
|
|
272
|
+
const url = new URL(request.url);
|
|
273
|
+
if (origin !== url.origin)
|
|
274
|
+
return refusal(403, `Origin ${origin} is not allowed.`, `Add ${JSON.stringify(origin)} to createMcp's allowedOrigins, or call the endpoint without a browser Origin.`);
|
|
275
|
+
const host = request.headers.get("host") ?? url.host;
|
|
276
|
+
const checked = validateHostHeader(host, [...policy.allowedHosts]);
|
|
277
|
+
if (checked.ok)
|
|
278
|
+
return;
|
|
279
|
+
return refusal(403, `Host ${host} is not allowed.`, `Add ${JSON.stringify(checked.hostname ?? host)} to createMcp's allowedHosts (hostnames without port). Behind a proxy, list the public hostname.`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/origin-options.ts
|
|
283
|
+
import { GraxiaConfigError as GraxiaConfigError2 } from "@graxia/core";
|
|
284
|
+
function hostnameOf(entry) {
|
|
285
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(entry)) {
|
|
286
|
+
const url = URL.parse(entry);
|
|
287
|
+
return url ? url.hostname : entry.replace(/^[^/]*\/\//, "").split(/[/:]/)[0];
|
|
288
|
+
}
|
|
289
|
+
if (entry.includes("/"))
|
|
290
|
+
return entry.split("/")[0]?.replace(/:\d+$/, "");
|
|
291
|
+
if (/^\[.*\](:\d+)$/.test(entry))
|
|
292
|
+
return entry.replace(/:\d+$/, "");
|
|
293
|
+
if (!entry.startsWith("[") && entry.split(":").length === 2 && /:\d+$/.test(entry))
|
|
294
|
+
return entry.replace(/:\d+$/, "");
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
function originOf(entry) {
|
|
298
|
+
const url = URL.parse(entry);
|
|
299
|
+
if (!url || url.origin === "null")
|
|
300
|
+
return;
|
|
301
|
+
return url.origin === entry ? undefined : url.origin;
|
|
302
|
+
}
|
|
303
|
+
function checkOriginOptions(allowedHosts, allowedOrigins) {
|
|
304
|
+
for (const entry of allowedHosts ?? []) {
|
|
305
|
+
const fixed = hostnameOf(entry);
|
|
306
|
+
if (fixed !== undefined)
|
|
307
|
+
throw new GraxiaConfigError2(`createMcp: allowedHosts entry "${entry}" can never match: it is a hostname without scheme, port or path. Fix: use "${fixed}".`);
|
|
308
|
+
}
|
|
309
|
+
for (const entry of allowedOrigins ?? []) {
|
|
310
|
+
const fixed = originOf(entry);
|
|
311
|
+
if (fixed !== undefined)
|
|
312
|
+
throw new GraxiaConfigError2(`createMcp: allowedOrigins entry "${entry}" can never match: an origin is exactly scheme://host[:port], no path and no trailing slash. Fix: use "${fixed}".`);
|
|
313
|
+
if (!URL.canParse(entry))
|
|
314
|
+
throw new GraxiaConfigError2(`createMcp: allowedOrigins entry "${entry}" is not an origin. Fix: use scheme://host[:port], e.g. "https://app.example".`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// src/body.ts
|
|
319
|
+
var TOO_LARGE = (max) => refusal(413, `The request body is larger than ${max} bytes.`, "Send a smaller request, or raise limits.bodyBytes of the graxia instance (this endpoint enforces the same).");
|
|
320
|
+
async function boundedRequest(request, max) {
|
|
321
|
+
const type = request.headers.get("content-type") ?? "";
|
|
322
|
+
if (!/^application\/json\s*(;|$)/i.test(type))
|
|
323
|
+
return refusal(415, "The request body must be application/json.", "Send the JSON-RPC message with the header Content-Type: application/json.");
|
|
324
|
+
const declared = Number(request.headers.get("content-length"));
|
|
325
|
+
if (declared > max)
|
|
326
|
+
return TOO_LARGE(max);
|
|
327
|
+
const chunks = [];
|
|
328
|
+
let size = 0;
|
|
329
|
+
if (request.body) {
|
|
330
|
+
for await (const chunk of request.body) {
|
|
331
|
+
size += chunk.byteLength;
|
|
332
|
+
if (size > max)
|
|
333
|
+
return TOO_LARGE(max);
|
|
334
|
+
chunks.push(chunk);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const bytes = new Uint8Array(size);
|
|
338
|
+
let at = 0;
|
|
339
|
+
for (const chunk of chunks) {
|
|
340
|
+
bytes.set(chunk, at);
|
|
341
|
+
at += chunk.byteLength;
|
|
342
|
+
}
|
|
343
|
+
return new Request(request.url, {
|
|
344
|
+
method: request.method,
|
|
345
|
+
headers: request.headers,
|
|
346
|
+
body: bytes,
|
|
347
|
+
signal: request.signal
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// src/pipeline.ts
|
|
352
|
+
async function admit(request, settings, gate) {
|
|
353
|
+
const forbidden = checkOrigin(request, settings);
|
|
354
|
+
if (forbidden)
|
|
355
|
+
return forbidden;
|
|
356
|
+
const cors = corsOrigin(request, settings.allowedOrigins);
|
|
357
|
+
if (request.method === "OPTIONS" && cors !== undefined)
|
|
358
|
+
return preflight(cors, request.headers.get("access-control-request-headers"));
|
|
359
|
+
if (request.method !== "POST")
|
|
360
|
+
return refusal(405, `${request.method} is not supported: this endpoint is stateless.`, "Send the JSON-RPC message with POST. There is no server-initiated stream to open or session to close.", { allow: "POST" });
|
|
361
|
+
const gated = gate ? await gate(request) : undefined;
|
|
362
|
+
if (gated instanceof Response)
|
|
363
|
+
return gated;
|
|
364
|
+
const bounded = await boundedRequest(request, settings.maxBody);
|
|
365
|
+
return bounded instanceof Response ? bounded : { request: bounded, gated };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// src/server.ts
|
|
369
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
370
|
+
|
|
371
|
+
// src/tools/execute.ts
|
|
372
|
+
import { GraxiaExecuteError } from "@graxia/core";
|
|
373
|
+
import { validate } from "graphql";
|
|
374
|
+
|
|
375
|
+
// src/tools/operation.ts
|
|
376
|
+
import {
|
|
377
|
+
FieldsOnCorrectTypeRule,
|
|
378
|
+
Kind,
|
|
379
|
+
KnownArgumentNamesRule,
|
|
380
|
+
KnownTypeNamesRule,
|
|
381
|
+
NoSchemaIntrospectionCustomRule,
|
|
382
|
+
PossibleFragmentSpreadsRule,
|
|
383
|
+
parse,
|
|
384
|
+
visit
|
|
385
|
+
} from "graphql";
|
|
386
|
+
function incrementalDirective(document) {
|
|
387
|
+
let found;
|
|
388
|
+
visit(document, {
|
|
389
|
+
Directive(node) {
|
|
390
|
+
if (node.name.value === "defer" || node.name.value === "stream")
|
|
391
|
+
found ??= node.name.value;
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
return found;
|
|
395
|
+
}
|
|
396
|
+
var VIEW_RULES = [
|
|
397
|
+
FieldsOnCorrectTypeRule,
|
|
398
|
+
KnownTypeNamesRule,
|
|
399
|
+
KnownArgumentNamesRule,
|
|
400
|
+
PossibleFragmentSpreadsRule,
|
|
401
|
+
NoSchemaIntrospectionCustomRule
|
|
402
|
+
];
|
|
403
|
+
var INTROSPECTION_FIX = "Use graphql_schema to read the schema.";
|
|
404
|
+
function parseOperation(query, tokens) {
|
|
405
|
+
try {
|
|
406
|
+
return {
|
|
407
|
+
document: parse(query, tokens === false ? {} : { maxTokens: tokens })
|
|
408
|
+
};
|
|
409
|
+
} catch (error) {
|
|
410
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
411
|
+
const overflow = /more than \d+ tokens/.test(message);
|
|
412
|
+
return {
|
|
413
|
+
refusal: {
|
|
414
|
+
message,
|
|
415
|
+
code: "GRAPHQL_PARSE_FAILED",
|
|
416
|
+
fix: overflow ? "Split the operation or raise limits.tokens." : "Correct the syntax of the document at the position the error points to."
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
var wrongKind = (allowed, found, writeScope) => {
|
|
422
|
+
if (found === "subscription")
|
|
423
|
+
return {
|
|
424
|
+
message: "Subscriptions are not available over MCP.",
|
|
425
|
+
code: "SUBSCRIPTION_NOT_SUPPORTED",
|
|
426
|
+
fix: "Send a query (graphql_query), or poll the same query again."
|
|
427
|
+
};
|
|
428
|
+
return {
|
|
429
|
+
message: `A ${found} cannot run in graphql_${allowed === "query" ? "query" : "mutate"}.`,
|
|
430
|
+
code: "MCP_OPERATION_NOT_ALLOWED",
|
|
431
|
+
fix: found === "mutation" ? `Use graphql_mutate for mutations (it is listed only when the server enables mutations${writeScope ? ` and the token has the scope ${writeScope}` : ""}).` : "Use graphql_query for queries."
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
function selected(document, operationName) {
|
|
435
|
+
const operations = document.definitions.filter((definition) => definition.kind === Kind.OPERATION_DEFINITION);
|
|
436
|
+
if (operationName)
|
|
437
|
+
return operations.find((o) => o.name?.value === operationName);
|
|
438
|
+
return operations.length === 1 ? operations[0] : undefined;
|
|
439
|
+
}
|
|
440
|
+
function checkOperations(document, allowed, operationName, writeScope) {
|
|
441
|
+
const operation = selected(document, operationName);
|
|
442
|
+
if (operation && operation.operation !== allowed)
|
|
443
|
+
return wrongKind(allowed, operation.operation, writeScope);
|
|
444
|
+
const incremental = incrementalDirective(document);
|
|
445
|
+
if (incremental)
|
|
446
|
+
return {
|
|
447
|
+
message: `@${incremental} is not available over MCP.`,
|
|
448
|
+
code: "INCREMENTAL_NOT_SUPPORTED",
|
|
449
|
+
fix: `Remove @${incremental}: the tool returns one complete JSON result.`
|
|
450
|
+
};
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// src/tools/result.ts
|
|
455
|
+
function resultOf(result) {
|
|
456
|
+
return {
|
|
457
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
458
|
+
structuredContent: result,
|
|
459
|
+
...result.data == null ? { isError: true } : {}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function refused(message, code, fix) {
|
|
463
|
+
return resultOf({ errors: [{ message, extensions: { code, fix } }] });
|
|
464
|
+
}
|
|
465
|
+
var textResult = (text, isError = false) => ({
|
|
466
|
+
content: [{ type: "text", text }],
|
|
467
|
+
...isError ? { isError: true } : {}
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
// src/tools/execute.ts
|
|
471
|
+
var SCHEMA_FIX = "Call graphql_schema (with { types: [...] } or { search }) to see the fields and arguments you may use, then correct the operation.";
|
|
472
|
+
var plain = (value) => JSON.parse(JSON.stringify(value));
|
|
473
|
+
async function errorsOf(error) {
|
|
474
|
+
try {
|
|
475
|
+
const body = await error.response.clone().json();
|
|
476
|
+
if (Array.isArray(body?.errors) && body.errors.length > 0)
|
|
477
|
+
return resultOf({ errors: body.errors });
|
|
478
|
+
} catch {}
|
|
479
|
+
return refused(error.message, "MCP_EXECUTION_REFUSED", "Retry later; if it persists, the server is shutting down or a plugin refused the request.");
|
|
480
|
+
}
|
|
481
|
+
async function runOperation(kind, input, context) {
|
|
482
|
+
const parsed = parseOperation(input.query, context.graxia.limits.tokens);
|
|
483
|
+
if ("refusal" in parsed)
|
|
484
|
+
return refused(parsed.refusal.message, parsed.refusal.code, parsed.refusal.fix);
|
|
485
|
+
const { document } = parsed;
|
|
486
|
+
const refusal = checkOperations(document, kind, input.operationName, context.writeScope);
|
|
487
|
+
if (refusal)
|
|
488
|
+
return refused(refusal.message, refusal.code, refusal.fix);
|
|
489
|
+
const problems = validate((await context.view()).schema, document, VIEW_RULES);
|
|
490
|
+
if (problems.length > 0)
|
|
491
|
+
return resultOf({
|
|
492
|
+
errors: problems.map((error) => ({
|
|
493
|
+
...plain(error),
|
|
494
|
+
extensions: {
|
|
495
|
+
code: "GRAPHQL_VALIDATION_FAILED",
|
|
496
|
+
fix: /introspection/i.test(error.message) ? INTROSPECTION_FIX : SCHEMA_FIX
|
|
497
|
+
}
|
|
498
|
+
}))
|
|
499
|
+
});
|
|
500
|
+
return execute(context, {
|
|
501
|
+
document: input.query,
|
|
502
|
+
variables: input.variables,
|
|
503
|
+
operationName: input.operationName
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
async function execute(context, operation) {
|
|
507
|
+
try {
|
|
508
|
+
const result = await context.graxia.execute({
|
|
509
|
+
document: operation.document,
|
|
510
|
+
...operation.variables ? { variables: operation.variables } : {},
|
|
511
|
+
...operation.operationName ? { operationName: operation.operationName } : {},
|
|
512
|
+
headers: context.headers,
|
|
513
|
+
...context.signal ? { signal: context.signal } : {},
|
|
514
|
+
serverContext: context.serverContext
|
|
515
|
+
});
|
|
516
|
+
return resultOf(plain(result));
|
|
517
|
+
} catch (error) {
|
|
518
|
+
if (error instanceof GraxiaExecuteError)
|
|
519
|
+
return errorsOf(error);
|
|
520
|
+
throw error;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/tools/guard.ts
|
|
525
|
+
var failed = () => textResult("The server failed to run the operation. Fix: retry later.", true);
|
|
526
|
+
async function guarded(context, run) {
|
|
527
|
+
try {
|
|
528
|
+
return await run();
|
|
529
|
+
} catch (error) {
|
|
530
|
+
context.onError(error);
|
|
531
|
+
return failed();
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// src/operations/register.ts
|
|
536
|
+
function advertised(schema) {
|
|
537
|
+
return {
|
|
538
|
+
"~standard": {
|
|
539
|
+
version: 1,
|
|
540
|
+
vendor: "graxia",
|
|
541
|
+
jsonSchema: { input: () => schema, output: () => schema },
|
|
542
|
+
validate: (value) => ({ value })
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
var ARGUMENTS_FIX = "Correct the arguments: see the tool's input schema.";
|
|
547
|
+
function unknownArguments(tool, variables) {
|
|
548
|
+
const accepted = Object.keys(tool.inputSchema["properties"] ?? {});
|
|
549
|
+
const unknown = Object.keys(variables).filter((key) => !accepted.includes(key));
|
|
550
|
+
if (unknown.length === 0)
|
|
551
|
+
return;
|
|
552
|
+
return refused(`${tool.name} does not take the argument${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}.`, "MCP_UNKNOWN_ARGUMENT", accepted.length > 0 ? `Send only the arguments the tool accepts: ${accepted.join(", ")}.` : "Send no argument: the tool takes none.");
|
|
553
|
+
}
|
|
554
|
+
function withArgumentsFix(result) {
|
|
555
|
+
const body = result.structuredContent;
|
|
556
|
+
const wrong = (error) => error["path"] === undefined && error["extensions"]?.code === "BAD_USER_INPUT";
|
|
557
|
+
if (!body?.errors?.some(wrong))
|
|
558
|
+
return result;
|
|
559
|
+
return resultOf({
|
|
560
|
+
...body,
|
|
561
|
+
errors: body.errors.map((error) => wrong(error) ? {
|
|
562
|
+
...error,
|
|
563
|
+
extensions: {
|
|
564
|
+
...error["extensions"],
|
|
565
|
+
fix: ARGUMENTS_FIX
|
|
566
|
+
}
|
|
567
|
+
} : error)
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
function registerOperationTools(server, tools, context) {
|
|
571
|
+
for (const tool of tools)
|
|
572
|
+
server.registerTool(tool.name, {
|
|
573
|
+
title: tool.title,
|
|
574
|
+
description: tool.description,
|
|
575
|
+
inputSchema: advertised(tool.inputSchema),
|
|
576
|
+
outputSchema: advertised(tool.outputSchema),
|
|
577
|
+
annotations: tool.kind === "query" ? { readOnlyHint: true } : { readOnlyHint: false, destructiveHint: true }
|
|
578
|
+
}, (variables = {}) => guarded(context, async () => unknownArguments(tool, variables) ?? withArgumentsFix(await execute(context, {
|
|
579
|
+
document: tool.source,
|
|
580
|
+
operationName: tool.title,
|
|
581
|
+
variables
|
|
582
|
+
}))));
|
|
583
|
+
}
|
|
584
|
+
function registerFailedTools(server, tools) {
|
|
585
|
+
for (const tool of tools)
|
|
586
|
+
server.registerTool(tool.name, { inputSchema: advertised({ type: "object" }) }, async () => failed());
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// src/tools/index.ts
|
|
590
|
+
import { z } from "zod";
|
|
591
|
+
|
|
592
|
+
// src/tools/schema.ts
|
|
593
|
+
import {
|
|
594
|
+
isEnumType,
|
|
595
|
+
isInputObjectType,
|
|
596
|
+
isInterfaceType,
|
|
597
|
+
isObjectType
|
|
598
|
+
} from "graphql";
|
|
599
|
+
|
|
600
|
+
// src/view.ts
|
|
601
|
+
import { printSchemaFor } from "@graxia/core/agent";
|
|
602
|
+
import {
|
|
603
|
+
buildSchema,
|
|
604
|
+
Kind as Kind2,
|
|
605
|
+
parse as parse2
|
|
606
|
+
} from "graphql";
|
|
607
|
+
var nameOf = (definition) => ("name" in definition) ? definition.name?.value : undefined;
|
|
608
|
+
function buildView(schema, can) {
|
|
609
|
+
const sdl = printSchemaFor(schema, can ? { can } : {});
|
|
610
|
+
const types = new Map;
|
|
611
|
+
const directives = new Map;
|
|
612
|
+
for (const definition of parse2(sdl, { noLocation: false }).definitions) {
|
|
613
|
+
const name = nameOf(definition);
|
|
614
|
+
const loc = definition.loc;
|
|
615
|
+
if (name === undefined || !loc)
|
|
616
|
+
continue;
|
|
617
|
+
const text = sdl.slice(loc.start, loc.end);
|
|
618
|
+
if (definition.kind === Kind2.DIRECTIVE_DEFINITION)
|
|
619
|
+
directives.set(name, text);
|
|
620
|
+
else if (definition.kind !== Kind2.SCHEMA_DEFINITION)
|
|
621
|
+
types.set(name, text);
|
|
622
|
+
}
|
|
623
|
+
return { schema: buildSchema(sdl), types, directives };
|
|
624
|
+
}
|
|
625
|
+
function directivesUsedBy(view, texts) {
|
|
626
|
+
const joined = texts.join(`
|
|
627
|
+
`);
|
|
628
|
+
return [...view.directives].filter(([name]) => new RegExp(`@${name}\\b`).test(joined)).map(([, text]) => text);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/tools/schema.ts
|
|
632
|
+
var SEARCH_LIMIT = 50;
|
|
633
|
+
var firstLine = (text) => text ? ` — ${text.trim().split(`
|
|
634
|
+
`)[0]}` : "";
|
|
635
|
+
function rootBlock(label, type) {
|
|
636
|
+
if (!type)
|
|
637
|
+
return [];
|
|
638
|
+
const lines = Object.values(type.getFields()).filter((field) => field.name !== "_empty").map((field) => {
|
|
639
|
+
const args = field.args.map((a) => `${a.name}: ${a.type}`).join(", ");
|
|
640
|
+
return ` ${field.name}${args ? `(${args})` : ""}: ${field.type}${firstLine(field.description)}`;
|
|
641
|
+
});
|
|
642
|
+
return lines.length > 0 ? [`${label}:`, ...lines, ""] : [];
|
|
643
|
+
}
|
|
644
|
+
function listed(view, mutations) {
|
|
645
|
+
const root = mutations ? undefined : view.schema.getMutationType()?.name;
|
|
646
|
+
return [...view.types.keys()].filter((name) => name !== root);
|
|
647
|
+
}
|
|
648
|
+
function overview(view, mutations, note = "") {
|
|
649
|
+
const { schema } = view;
|
|
650
|
+
const lines = [
|
|
651
|
+
...rootBlock("Query", schema.getQueryType() ?? undefined),
|
|
652
|
+
...mutations ? rootBlock("Mutation", schema.getMutationType() ?? undefined) : [],
|
|
653
|
+
`Types: ${listed(view, mutations).join(", ")}`,
|
|
654
|
+
"",
|
|
655
|
+
...note ? [note, ""] : [],
|
|
656
|
+
'Next: call graphql_schema with { types: ["Name"] } for the SDL of a type, or { search: "word" } to find types by name or description.'
|
|
657
|
+
];
|
|
658
|
+
return textResult(lines.join(`
|
|
659
|
+
`));
|
|
660
|
+
}
|
|
661
|
+
function sdlOf(view, names) {
|
|
662
|
+
const texts = names.map((name) => view.types.get(name));
|
|
663
|
+
return [...directivesUsedBy(view, texts), ...texts].join(`
|
|
664
|
+
|
|
665
|
+
`);
|
|
666
|
+
}
|
|
667
|
+
function typesSdl(view, names, mutations) {
|
|
668
|
+
const offered = new Set(listed(view, mutations));
|
|
669
|
+
const known = names.filter((name) => offered.has(name));
|
|
670
|
+
const unknown = names.filter((name) => !offered.has(name));
|
|
671
|
+
const notes = unknown.map((name) => `# Unknown type ${name}. Fix: call graphql_schema with no input to list the type names you can use.`);
|
|
672
|
+
const body = known.length > 0 ? sdlOf(view, known) : "";
|
|
673
|
+
return textResult([body, ...notes].filter(Boolean).join(`
|
|
674
|
+
|
|
675
|
+
`), known.length === 0);
|
|
676
|
+
}
|
|
677
|
+
function words(text) {
|
|
678
|
+
return text.toLowerCase().split(/[^\p{L}\p{N}_]+/u).filter(Boolean);
|
|
679
|
+
}
|
|
680
|
+
function haystack(type) {
|
|
681
|
+
const parts = [type.name, type.description];
|
|
682
|
+
if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type))
|
|
683
|
+
for (const field of Object.values(type.getFields()))
|
|
684
|
+
parts.push(field.name, field.description);
|
|
685
|
+
if (isEnumType(type))
|
|
686
|
+
for (const value of type.getValues())
|
|
687
|
+
parts.push(value.name, value.description);
|
|
688
|
+
return parts.filter(Boolean).join(" ").toLowerCase();
|
|
689
|
+
}
|
|
690
|
+
function searchSdl(view, search, mutations) {
|
|
691
|
+
const wanted = words(search);
|
|
692
|
+
if (wanted.length === 0)
|
|
693
|
+
return textResult("Empty search. Fix: pass a word of a type or field name or description, or call graphql_schema with no input for the overview.", true);
|
|
694
|
+
const matches = listed(view, mutations).filter((name) => {
|
|
695
|
+
const type = view.schema.getType(name);
|
|
696
|
+
if (!type)
|
|
697
|
+
return false;
|
|
698
|
+
const text = haystack(type);
|
|
699
|
+
return wanted.every((word) => text.includes(word));
|
|
700
|
+
});
|
|
701
|
+
if (matches.length === 0)
|
|
702
|
+
return textResult(`No type matches "${search}". Fix: try one word, or call graphql_schema with no input for the overview.`, true);
|
|
703
|
+
const shown = matches.slice(0, SEARCH_LIMIT);
|
|
704
|
+
const more = matches.length > shown.length ? `
|
|
705
|
+
|
|
706
|
+
# ${matches.length - shown.length} more types match. Fix: narrow the search with another word.` : "";
|
|
707
|
+
return textResult(sdlOf(view, shown) + more);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// src/tools/strict.ts
|
|
711
|
+
var strictFix = (typed) => typed.length > 0 ? `This server runs trusted documents only: use the typed tools (${typed.join(", ")}).` : "This server runs trusted documents only and offers you no typed tool: no operation can be run here.";
|
|
712
|
+
function registerStrictRefusals(server, typed) {
|
|
713
|
+
for (const name of ["graphql_query", "graphql_mutate"])
|
|
714
|
+
server.registerTool(name, { inputSchema: advertised({ type: "object" }) }, async () => refused("Only persisted documents are allowed.", "PERSISTED_QUERY_ONLY", strictFix(typed)));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// src/tools/index.ts
|
|
718
|
+
var operationInput = z.object({
|
|
719
|
+
query: z.string().describe("The GraphQL document (one operation)."),
|
|
720
|
+
variables: z.record(z.string(), z.unknown()).optional().describe("The operation variables, as a JSON object."),
|
|
721
|
+
operationName: z.string().optional().describe("Which operation to run when the document has several.")
|
|
722
|
+
});
|
|
723
|
+
var schemaInput = z.object({
|
|
724
|
+
search: z.string().optional().describe("Words to find in type and field names and descriptions."),
|
|
725
|
+
types: z.array(z.string()).max(SEARCH_LIMIT).optional().describe("Names of the types whose SDL to return.")
|
|
726
|
+
});
|
|
727
|
+
function registerTools(server, input) {
|
|
728
|
+
const { context, mutations, generic, typed } = input;
|
|
729
|
+
const note = typedNote(typed, generic);
|
|
730
|
+
server.registerTool("graphql_schema", {
|
|
731
|
+
title: "GraphQL schema",
|
|
732
|
+
description: 'Describe the GraphQL API you may use. CALL THIS FIRST. With no input: the available operations and the type names. With { types: ["Name"] }: the SDL of those types (descriptions, @needs permissions, @constraint limits and @errors codes included). With { search: "word" }: the types whose names or descriptions match. A name not shown here is not available to you.',
|
|
733
|
+
inputSchema: schemaInput,
|
|
734
|
+
annotations: { readOnlyHint: true }
|
|
735
|
+
}, (args) => guarded(context, async () => {
|
|
736
|
+
const view = await context.view();
|
|
737
|
+
if (args.types && args.types.length > 0)
|
|
738
|
+
return typesSdl(view, args.types, mutations);
|
|
739
|
+
if (args.search !== undefined)
|
|
740
|
+
return searchSdl(view, args.search, mutations);
|
|
741
|
+
return overview(view, mutations, note);
|
|
742
|
+
}));
|
|
743
|
+
if (generic === "refused" && !input.listing)
|
|
744
|
+
registerStrictRefusals(server, typed);
|
|
745
|
+
if (generic !== "on")
|
|
746
|
+
return;
|
|
747
|
+
server.registerTool("graphql_query", {
|
|
748
|
+
title: "GraphQL query",
|
|
749
|
+
description: "Run a GraphQL query (read only). Call graphql_schema first to learn the fields. Returns { data, errors }; every error has extensions.code and extensions.fix: read the fix. Mutations, subscriptions and introspection (__schema, __type) are refused: use graphql_schema to read the schema. @defer and @stream are not available.",
|
|
750
|
+
inputSchema: operationInput,
|
|
751
|
+
annotations: { readOnlyHint: true }
|
|
752
|
+
}, (args) => guarded(context, () => runOperation("query", args, context)));
|
|
753
|
+
if (!mutations)
|
|
754
|
+
return;
|
|
755
|
+
server.registerTool("graphql_mutate", {
|
|
756
|
+
title: "GraphQL mutation",
|
|
757
|
+
description: "Run a GraphQL mutation (it changes data). Call graphql_schema first to learn the mutations, their @needs permissions and @errors codes. Returns { data, errors }; every error has extensions.code and extensions.fix: read the fix. Queries are refused here: use graphql_query.",
|
|
758
|
+
inputSchema: operationInput,
|
|
759
|
+
annotations: { readOnlyHint: false, destructiveHint: true }
|
|
760
|
+
}, (args) => guarded(context, () => runOperation("mutation", args, context)));
|
|
761
|
+
}
|
|
762
|
+
function typedNote(typed, generic) {
|
|
763
|
+
if (typed.length === 0)
|
|
764
|
+
return generic === "refused" ? "No tool runs operations here: this server runs trusted documents only and offers you no typed tool." : "";
|
|
765
|
+
return generic === "on" ? `Typed tools: ${typed.join(", ")}. Prefer the typed tools: each runs one reviewed operation and takes typed arguments; use graphql_query for anything else.` : `Typed tools: ${typed.join(", ")}. They are the only way to run operations here.`;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// src/server.ts
|
|
769
|
+
var OWN_HEADERS = /^(content-type|content-length|accept|host|origin|connection|transfer-encoding|mcp-.*)$/i;
|
|
770
|
+
function forwardedHeaders(request) {
|
|
771
|
+
const headers = new Headers;
|
|
772
|
+
for (const [name, value] of request.headers)
|
|
773
|
+
if (!OWN_HEADERS.test(name))
|
|
774
|
+
headers.set(name, value);
|
|
775
|
+
return headers;
|
|
776
|
+
}
|
|
777
|
+
async function typedFor(settings, state, mutations) {
|
|
778
|
+
const { toolset, onError } = settings;
|
|
779
|
+
const { list, called } = state.calls;
|
|
780
|
+
if (toolset.typed.length === 0 || !(list || called.length > 0))
|
|
781
|
+
return { offered: [], failed: [] };
|
|
782
|
+
const mine = (tool) => mutations || tool.kind === "query";
|
|
783
|
+
try {
|
|
784
|
+
const visible = toolset.visible(await state.view());
|
|
785
|
+
return { offered: visible.filter(mine), failed: [] };
|
|
786
|
+
} catch (error) {
|
|
787
|
+
onError(error);
|
|
788
|
+
return { offered: [], failed: list ? [] : toolset.typed.filter(mine) };
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
function serverFactory(settings) {
|
|
792
|
+
const { graxia, options, auth, carrier, toolset, onError } = settings;
|
|
793
|
+
return async ({ requestInfo }) => {
|
|
794
|
+
const request = requestInfo;
|
|
795
|
+
const state = carrier.current();
|
|
796
|
+
const principal = mcpAuth();
|
|
797
|
+
const mutations = (options.mutations ?? false) && (auth === undefined || principal !== undefined && canWrite(auth, principal));
|
|
798
|
+
const typed = await typedFor(settings, state, mutations);
|
|
799
|
+
const context = {
|
|
800
|
+
graxia,
|
|
801
|
+
view: state.view,
|
|
802
|
+
serverContext: state.serverContext,
|
|
803
|
+
headers: forwardedHeaders(request),
|
|
804
|
+
signal: request.signal,
|
|
805
|
+
writeScope: auth?.write,
|
|
806
|
+
onError
|
|
807
|
+
};
|
|
808
|
+
const server = new McpServer({ name: options.name, version: options.version ?? "0.0.0" }, options.instructions ? { instructions: options.instructions } : undefined);
|
|
809
|
+
registerTools(server, {
|
|
810
|
+
context,
|
|
811
|
+
mutations,
|
|
812
|
+
generic: toolset.generic,
|
|
813
|
+
listing: state.calls.list,
|
|
814
|
+
typed: typed.offered.map((tool) => tool.name)
|
|
815
|
+
});
|
|
816
|
+
registerOperationTools(server, typed.offered, context);
|
|
817
|
+
registerFailedTools(server, typed.failed);
|
|
818
|
+
return server;
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// src/toolset.ts
|
|
823
|
+
import { GraxiaConfigError as GraxiaConfigError4 } from "@graxia/core";
|
|
824
|
+
|
|
825
|
+
// src/operations/build.ts
|
|
826
|
+
import {
|
|
827
|
+
Kind as Kind5,
|
|
828
|
+
NoSchemaIntrospectionCustomRule as NoSchemaIntrospectionCustomRule2,
|
|
829
|
+
parse as parse3,
|
|
830
|
+
specifiedRules,
|
|
831
|
+
validate as validate2
|
|
832
|
+
} from "graphql";
|
|
833
|
+
|
|
834
|
+
// src/operations/documents.ts
|
|
835
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
836
|
+
function manifestEntries(manifest) {
|
|
837
|
+
if (manifest instanceof Map)
|
|
838
|
+
return [...manifest].map(([id, source]) => ({ id: String(id), source }));
|
|
839
|
+
if (!isRecord(manifest))
|
|
840
|
+
return;
|
|
841
|
+
if (manifest["format"] === "apollo-persisted-query-manifest") {
|
|
842
|
+
const { operations } = manifest;
|
|
843
|
+
if (!Array.isArray(operations))
|
|
844
|
+
return;
|
|
845
|
+
return operations.map((operation, index) => ({
|
|
846
|
+
id: isRecord(operation) ? String(operation["id"]) : `#${index}`,
|
|
847
|
+
source: isRecord(operation) ? operation["body"] : undefined
|
|
848
|
+
}));
|
|
849
|
+
}
|
|
850
|
+
return Object.entries(manifest).map(([id, source]) => ({ id, source }));
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/operations/input-schema.ts
|
|
854
|
+
import {
|
|
855
|
+
isNonNullType as isNonNullType2,
|
|
856
|
+
typeFromAST,
|
|
857
|
+
valueFromASTUntyped as valueFromASTUntyped2
|
|
858
|
+
} from "graphql";
|
|
859
|
+
|
|
860
|
+
// src/operations/constraint.ts
|
|
861
|
+
var LEAF = {
|
|
862
|
+
minLength: "minLength",
|
|
863
|
+
maxLength: "maxLength",
|
|
864
|
+
min: "minimum",
|
|
865
|
+
max: "maximum",
|
|
866
|
+
exclusiveMin: "exclusiveMinimum",
|
|
867
|
+
exclusiveMax: "exclusiveMaximum",
|
|
868
|
+
multipleOf: "multipleOf",
|
|
869
|
+
pattern: "pattern",
|
|
870
|
+
format: "format"
|
|
871
|
+
};
|
|
872
|
+
var LIST = {
|
|
873
|
+
minItems: "minItems",
|
|
874
|
+
maxItems: "maxItems"
|
|
875
|
+
};
|
|
876
|
+
var LOWER = ["minLength", "min", "exclusiveMin", "minItems"];
|
|
877
|
+
var UPPER = ["maxLength", "max", "exclusiveMax", "maxItems"];
|
|
878
|
+
var EXACT = ["multipleOf", "pattern", "format"];
|
|
879
|
+
var isArray = (node) => node["type"] === "array" || Array.isArray(node["type"]) && node["type"].includes("array");
|
|
880
|
+
function keywords(constraint, map) {
|
|
881
|
+
const out = {};
|
|
882
|
+
for (const [key, keyword] of Object.entries(map)) {
|
|
883
|
+
const value = constraint[key];
|
|
884
|
+
if (value !== undefined && value !== null)
|
|
885
|
+
out[keyword] = value;
|
|
886
|
+
}
|
|
887
|
+
return out;
|
|
888
|
+
}
|
|
889
|
+
function constrained(node, constraint) {
|
|
890
|
+
if (!constraint)
|
|
891
|
+
return node;
|
|
892
|
+
if (isArray(node))
|
|
893
|
+
return {
|
|
894
|
+
...node,
|
|
895
|
+
...keywords(constraint, LIST),
|
|
896
|
+
items: leafConstrained(node["items"], constraint)
|
|
897
|
+
};
|
|
898
|
+
return leafConstrained(node, constraint);
|
|
899
|
+
}
|
|
900
|
+
function leafConstrained(node, constraint) {
|
|
901
|
+
if (isArray(node))
|
|
902
|
+
return {
|
|
903
|
+
...node,
|
|
904
|
+
items: leafConstrained(node["items"], constraint)
|
|
905
|
+
};
|
|
906
|
+
if ("$ref" in node || "anyOf" in node)
|
|
907
|
+
return node;
|
|
908
|
+
return { ...node, ...keywords(constraint, LEAF) };
|
|
909
|
+
}
|
|
910
|
+
function tightest(constraints) {
|
|
911
|
+
if (constraints.length === 0)
|
|
912
|
+
return;
|
|
913
|
+
const out = {};
|
|
914
|
+
const values = (key) => constraints.map((c) => c[key]).filter((v) => v != null);
|
|
915
|
+
for (const key of LOWER)
|
|
916
|
+
if (values(key).length > 0)
|
|
917
|
+
out[key] = Math.max(...values(key));
|
|
918
|
+
for (const key of UPPER)
|
|
919
|
+
if (values(key).length > 0)
|
|
920
|
+
out[key] = Math.min(...values(key));
|
|
921
|
+
for (const key of EXACT) {
|
|
922
|
+
const distinct = new Set(values(key));
|
|
923
|
+
if (distinct.size === 1)
|
|
924
|
+
out[key] = [...distinct][0];
|
|
925
|
+
}
|
|
926
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// src/operations/input-type.ts
|
|
930
|
+
import { constraintOf } from "@graxia/core/agent";
|
|
931
|
+
import {
|
|
932
|
+
isEnumType as isEnumType2,
|
|
933
|
+
isInputObjectType as isInputObjectType2,
|
|
934
|
+
isListType,
|
|
935
|
+
isNonNullType,
|
|
936
|
+
isRequiredInputField,
|
|
937
|
+
valueFromASTUntyped
|
|
938
|
+
} from "graphql";
|
|
939
|
+
var newDefs = () => Object.create(null);
|
|
940
|
+
var SCALARS = {
|
|
941
|
+
Int: "integer",
|
|
942
|
+
Float: "number",
|
|
943
|
+
String: "string",
|
|
944
|
+
ID: "string",
|
|
945
|
+
Boolean: "boolean"
|
|
946
|
+
};
|
|
947
|
+
var described = (description) => description ? { description } : {};
|
|
948
|
+
function enumSchema(type) {
|
|
949
|
+
const values = type.getValues();
|
|
950
|
+
const lines = values.filter((value) => value.description).map((value) => `- ${value.name}: ${value.description}`);
|
|
951
|
+
const description = [type.description, ...lines].filter(Boolean).join(`
|
|
952
|
+
`);
|
|
953
|
+
return {
|
|
954
|
+
type: "string",
|
|
955
|
+
enum: values.map((value) => value.name),
|
|
956
|
+
...described(description)
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
function nullable(node) {
|
|
960
|
+
if ("$ref" in node)
|
|
961
|
+
return { anyOf: [node, { type: "null" }] };
|
|
962
|
+
if (typeof node["type"] !== "string")
|
|
963
|
+
return node;
|
|
964
|
+
return {
|
|
965
|
+
...node,
|
|
966
|
+
type: [node["type"], "null"],
|
|
967
|
+
...Array.isArray(node["enum"]) ? { enum: [...node["enum"], null] } : {}
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
function defaultOf(field) {
|
|
971
|
+
const declared = field.default;
|
|
972
|
+
if (declared?.literal)
|
|
973
|
+
return { default: valueFromASTUntyped(declared.literal) };
|
|
974
|
+
if (declared && "value" in declared)
|
|
975
|
+
return { default: declared.value };
|
|
976
|
+
if (field.defaultValue !== undefined)
|
|
977
|
+
return { default: field.defaultValue };
|
|
978
|
+
return {};
|
|
979
|
+
}
|
|
980
|
+
function fieldSchema(field, defs) {
|
|
981
|
+
return {
|
|
982
|
+
...constrained(typeSchema(field.type, defs), constraintOf(field)),
|
|
983
|
+
...described(field.description),
|
|
984
|
+
...defaultOf(field),
|
|
985
|
+
...field.deprecationReason ? { deprecated: true } : {}
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
function objectSchema(type, defs) {
|
|
989
|
+
const fields = Object.values(type.getFields());
|
|
990
|
+
if (type.isOneOf)
|
|
991
|
+
return {
|
|
992
|
+
type: "object",
|
|
993
|
+
...described(type.description),
|
|
994
|
+
oneOf: fields.map((field) => ({
|
|
995
|
+
properties: {
|
|
996
|
+
[field.name]: {
|
|
997
|
+
...constrained(valueSchema(field.type, defs), constraintOf(field)),
|
|
998
|
+
...described(field.description)
|
|
999
|
+
}
|
|
1000
|
+
},
|
|
1001
|
+
required: [field.name],
|
|
1002
|
+
additionalProperties: false
|
|
1003
|
+
}))
|
|
1004
|
+
};
|
|
1005
|
+
const required = fields.filter(isRequiredInputField).map((f) => f.name);
|
|
1006
|
+
return {
|
|
1007
|
+
type: "object",
|
|
1008
|
+
...described(type.description),
|
|
1009
|
+
properties: Object.fromEntries(fields.map((field) => [field.name, fieldSchema(field, defs)])),
|
|
1010
|
+
...required.length > 0 ? { required } : {},
|
|
1011
|
+
additionalProperties: false
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
function valueSchema(type, defs) {
|
|
1015
|
+
if (isNonNullType(type))
|
|
1016
|
+
return valueSchema(type.ofType, defs);
|
|
1017
|
+
if (isListType(type))
|
|
1018
|
+
return { type: "array", items: typeSchema(type.ofType, defs) };
|
|
1019
|
+
if (isEnumType2(type))
|
|
1020
|
+
return enumSchema(type);
|
|
1021
|
+
if (isInputObjectType2(type)) {
|
|
1022
|
+
if (!Object.hasOwn(defs, type.name)) {
|
|
1023
|
+
defs[type.name] = {};
|
|
1024
|
+
defs[type.name] = objectSchema(type, defs);
|
|
1025
|
+
}
|
|
1026
|
+
return { $ref: `#/$defs/${type.name}` };
|
|
1027
|
+
}
|
|
1028
|
+
const builtIn = SCALARS[type.name];
|
|
1029
|
+
return builtIn ? { type: builtIn } : described(type.description);
|
|
1030
|
+
}
|
|
1031
|
+
function typeSchema(type, defs) {
|
|
1032
|
+
return isNonNullType(type) ? valueSchema(type.ofType, defs) : nullable(valueSchema(type, defs));
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// src/operations/variable-usage.ts
|
|
1036
|
+
import { constraintOf as constraintOf2 } from "@graxia/core/agent";
|
|
1037
|
+
import {
|
|
1038
|
+
getNamedType,
|
|
1039
|
+
isInputObjectType as isInputObjectType3,
|
|
1040
|
+
Kind as Kind3,
|
|
1041
|
+
TypeInfo,
|
|
1042
|
+
visit as visit2,
|
|
1043
|
+
visitWithTypeInfo
|
|
1044
|
+
} from "graphql";
|
|
1045
|
+
function reachable(document, operation) {
|
|
1046
|
+
const fragments = new Map;
|
|
1047
|
+
for (const definition of document.definitions)
|
|
1048
|
+
if (definition.kind === Kind3.FRAGMENT_DEFINITION)
|
|
1049
|
+
fragments.set(definition.name.value, definition);
|
|
1050
|
+
const reached = new Set;
|
|
1051
|
+
const follow = (node) => visit2(node, {
|
|
1052
|
+
FragmentSpread(spread) {
|
|
1053
|
+
const fragment = fragments.get(spread.name.value);
|
|
1054
|
+
if (!fragment || reached.has(fragment))
|
|
1055
|
+
return;
|
|
1056
|
+
reached.add(fragment);
|
|
1057
|
+
follow(fragment);
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
1060
|
+
follow(operation);
|
|
1061
|
+
return { kind: Kind3.DOCUMENT, definitions: [operation, ...reached] };
|
|
1062
|
+
}
|
|
1063
|
+
function variableUsages(schema, document, operation) {
|
|
1064
|
+
const usages = new Map;
|
|
1065
|
+
const note = (name, target) => {
|
|
1066
|
+
const usage = usages.get(name) ?? { constraints: [] };
|
|
1067
|
+
const constraint = constraintOf2(target);
|
|
1068
|
+
if (constraint)
|
|
1069
|
+
usage.constraints.push(constraint);
|
|
1070
|
+
if (usage.description === undefined && target.description)
|
|
1071
|
+
usage.description = target.description;
|
|
1072
|
+
usages.set(name, usage);
|
|
1073
|
+
};
|
|
1074
|
+
const typeInfo = new TypeInfo(schema);
|
|
1075
|
+
visit2(reachable(document, operation), visitWithTypeInfo(typeInfo, {
|
|
1076
|
+
Variable(node, _key, parent) {
|
|
1077
|
+
if (!parent || Array.isArray(parent))
|
|
1078
|
+
return;
|
|
1079
|
+
const holder = parent;
|
|
1080
|
+
if (holder.kind === Kind3.ARGUMENT) {
|
|
1081
|
+
const argument = typeInfo.getArgument();
|
|
1082
|
+
if (argument)
|
|
1083
|
+
note(node.name.value, argument);
|
|
1084
|
+
} else if (holder.kind === Kind3.OBJECT_FIELD) {
|
|
1085
|
+
const object = typeInfo.getParentInputType();
|
|
1086
|
+
const named = object ? getNamedType(object) : undefined;
|
|
1087
|
+
const field = isInputObjectType3(named) ? named.getFields()[holder.name?.value ?? ""] : undefined;
|
|
1088
|
+
if (field)
|
|
1089
|
+
note(node.name.value, field);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
}));
|
|
1093
|
+
return usages;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// src/operations/input-schema.ts
|
|
1097
|
+
function inputSchemaOf(schema, document, operation) {
|
|
1098
|
+
const defs = newDefs();
|
|
1099
|
+
const usages = variableUsages(schema, document, operation);
|
|
1100
|
+
const properties = {};
|
|
1101
|
+
const required = [];
|
|
1102
|
+
for (const definition of operation.variableDefinitions ?? []) {
|
|
1103
|
+
const name = definition.variable.name.value;
|
|
1104
|
+
const type = typeFromAST(schema, definition.type);
|
|
1105
|
+
if (!type)
|
|
1106
|
+
continue;
|
|
1107
|
+
const usage = usages.get(name);
|
|
1108
|
+
const description = definition.description?.value ?? usage?.description;
|
|
1109
|
+
properties[name] = {
|
|
1110
|
+
...constrained(typeSchema(type, defs), tightest(usage?.constraints ?? [])),
|
|
1111
|
+
...description ? { description } : {},
|
|
1112
|
+
...definition.defaultValue ? { default: valueFromASTUntyped2(definition.defaultValue) } : {}
|
|
1113
|
+
};
|
|
1114
|
+
if (isNonNullType2(type) && !definition.defaultValue)
|
|
1115
|
+
required.push(name);
|
|
1116
|
+
}
|
|
1117
|
+
return {
|
|
1118
|
+
type: "object",
|
|
1119
|
+
properties,
|
|
1120
|
+
...required.length > 0 ? { required } : {},
|
|
1121
|
+
additionalProperties: false,
|
|
1122
|
+
...Object.keys(defs).length > 0 ? { $defs: defs } : {}
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// src/operations/naming.ts
|
|
1127
|
+
function toolNameOf(operationName) {
|
|
1128
|
+
return operationName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
|
|
1129
|
+
}
|
|
1130
|
+
var RESERVED_PREFIX = "graphql_";
|
|
1131
|
+
|
|
1132
|
+
// src/operations/output-schema.ts
|
|
1133
|
+
import {
|
|
1134
|
+
isAbstractType,
|
|
1135
|
+
isCompositeType,
|
|
1136
|
+
isEnumType as isEnumType3,
|
|
1137
|
+
isListType as isListType2,
|
|
1138
|
+
isNonNullType as isNonNullType3,
|
|
1139
|
+
isObjectType as isObjectType2,
|
|
1140
|
+
isUnionType,
|
|
1141
|
+
Kind as Kind4
|
|
1142
|
+
} from "graphql";
|
|
1143
|
+
var ERRORS = {
|
|
1144
|
+
type: "array",
|
|
1145
|
+
items: {
|
|
1146
|
+
type: "object",
|
|
1147
|
+
properties: {
|
|
1148
|
+
message: { type: "string" },
|
|
1149
|
+
path: { type: "array", items: { type: ["string", "integer"] } },
|
|
1150
|
+
extensions: {
|
|
1151
|
+
type: "object",
|
|
1152
|
+
properties: { code: { type: "string" }, fix: { type: "string" } }
|
|
1153
|
+
}
|
|
1154
|
+
},
|
|
1155
|
+
required: ["message"]
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
var conditional = (node) => (node.directives ?? []).some((d) => d.name.value === "skip" || d.name.value === "include");
|
|
1159
|
+
function covers(schema, parent, condition) {
|
|
1160
|
+
if (condition === parent || isObjectType2(parent))
|
|
1161
|
+
return true;
|
|
1162
|
+
return schema.getPossibleTypes(parent).every((t) => isAbstractType(condition) ? schema.isSubType(condition, t) : t === condition);
|
|
1163
|
+
}
|
|
1164
|
+
function collect(walk, parent, set, always, origin, slots) {
|
|
1165
|
+
for (const selection of set.selections) {
|
|
1166
|
+
const sure = always && !conditional(selection);
|
|
1167
|
+
if (selection.kind === Kind4.FIELD) {
|
|
1168
|
+
const key = selection.alias?.value ?? selection.name.value;
|
|
1169
|
+
const slot = slots.get(key) ?? {
|
|
1170
|
+
sureIn: new Set,
|
|
1171
|
+
typename: false,
|
|
1172
|
+
byType: new Map
|
|
1173
|
+
};
|
|
1174
|
+
slots.set(key, slot);
|
|
1175
|
+
if (sure)
|
|
1176
|
+
slot.sureIn.add(origin);
|
|
1177
|
+
const field = isUnionType(parent) ? undefined : parent.getFields()[selection.name.value];
|
|
1178
|
+
if (!field) {
|
|
1179
|
+
slot.typename = true;
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
const group = slot.byType.get(String(field.type)) ?? {
|
|
1183
|
+
type: field.type,
|
|
1184
|
+
nodes: []
|
|
1185
|
+
};
|
|
1186
|
+
group.nodes.push({ node: selection, sure: sure && origin.sure });
|
|
1187
|
+
slot.byType.set(String(field.type), group);
|
|
1188
|
+
continue;
|
|
1189
|
+
}
|
|
1190
|
+
const fragment = selection.kind === Kind4.FRAGMENT_SPREAD ? walk.fragments.get(selection.name.value) : selection;
|
|
1191
|
+
if (!fragment)
|
|
1192
|
+
continue;
|
|
1193
|
+
const named = fragment.typeCondition ? walk.schema.getType(fragment.typeCondition.name.value) : parent;
|
|
1194
|
+
if (!isCompositeType(named))
|
|
1195
|
+
continue;
|
|
1196
|
+
collect(walk, named, fragment.selectionSet, sure && covers(walk.schema, parent, named), origin, slots);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
function objectOf(walk, parent, origins) {
|
|
1200
|
+
const slots = new Map;
|
|
1201
|
+
for (const origin of origins)
|
|
1202
|
+
collect(walk, parent, origin.set, true, origin, slots);
|
|
1203
|
+
const properties = {};
|
|
1204
|
+
for (const [key, slot] of slots) {
|
|
1205
|
+
const shapes = [...slot.byType.values()].map((group) => typeOf(walk, group.type, group.nodes));
|
|
1206
|
+
if (slot.typename)
|
|
1207
|
+
shapes.unshift({ type: "string" });
|
|
1208
|
+
properties[key] = shapes.length === 1 ? shapes[0] : { anyOf: shapes };
|
|
1209
|
+
}
|
|
1210
|
+
const required = [...slots].filter(([, slot]) => slot.sureIn.size === origins.length || [...slot.sureIn].some((origin) => origin.sure)).map(([key]) => key);
|
|
1211
|
+
return {
|
|
1212
|
+
type: "object",
|
|
1213
|
+
properties,
|
|
1214
|
+
...required.length > 0 ? { required } : {}
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
function shapeOf(walk, type, nodes) {
|
|
1218
|
+
if (isNonNullType3(type))
|
|
1219
|
+
return shapeOf(walk, type.ofType, nodes);
|
|
1220
|
+
if (isListType2(type))
|
|
1221
|
+
return { type: "array", items: typeOf(walk, type.ofType, nodes) };
|
|
1222
|
+
if (isCompositeType(type))
|
|
1223
|
+
return objectOf(walk, type, nodes.flatMap(({ node, sure }) => node.selectionSet ? [{ set: node.selectionSet, sure }] : []));
|
|
1224
|
+
if (isEnumType3(type))
|
|
1225
|
+
return enumSchema(type);
|
|
1226
|
+
const builtIn = SCALARS[type.name];
|
|
1227
|
+
return builtIn ? { type: builtIn } : {};
|
|
1228
|
+
}
|
|
1229
|
+
var typeOf = (walk, type, nodes) => isNonNullType3(type) ? shapeOf(walk, type.ofType, nodes) : nullable(shapeOf(walk, type, nodes));
|
|
1230
|
+
function outputSchemaOf(schema, document, operation) {
|
|
1231
|
+
const fragments = new Map;
|
|
1232
|
+
for (const definition of document.definitions)
|
|
1233
|
+
if (definition.kind === Kind4.FRAGMENT_DEFINITION)
|
|
1234
|
+
fragments.set(definition.name.value, definition);
|
|
1235
|
+
const root = schema.getRootType(operation.operation);
|
|
1236
|
+
const data = root ? nullable(objectOf({ schema, fragments }, root, [
|
|
1237
|
+
{ set: operation.selectionSet, sure: true }
|
|
1238
|
+
])) : {};
|
|
1239
|
+
return { type: "object", properties: { data, errors: ERRORS } };
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
// src/operations/problems.ts
|
|
1243
|
+
import { GraxiaConfigError as GraxiaConfigError3 } from "@graxia/core";
|
|
1244
|
+
var EXCLUDE = "or leave it out with operations.include";
|
|
1245
|
+
var MAX_TOOL_NAME = 128;
|
|
1246
|
+
var problem = {
|
|
1247
|
+
manifest: () => "operations.documents is not a manifest. Fix: pass a Map, an object of id to source (persisted-documents.json), or an Apollo persisted query manifest.",
|
|
1248
|
+
source: (id) => `document "${id}" is not a GraphQL source string. Fix: map every id to the text of its document.`,
|
|
1249
|
+
parse: (id, message) => `document "${id}" does not parse: ${message} Fix: regenerate the manifest; if it comes from another server's schema, do not pass it here.`,
|
|
1250
|
+
anonymous: (id) => `document "${id}" holds an anonymous operation: a tool needs a name. Fix: name it (query BookById { ... }) and regenerate the manifest.`,
|
|
1251
|
+
invalid: (names, id, messages) => `${names.join(", ")} (document "${id}") is not valid against the schema: ${messages.join(" ")} Fix: regenerate the manifest from the current schema, ${EXCLUDE}.`,
|
|
1252
|
+
introspection: (names, id) => `${names.join(", ")} (document "${id}") selects __schema or __type: introspection is not offered over MCP, an agent reads the schema with graphql_schema. Fix: leave the operation out with operations.include.`,
|
|
1253
|
+
incremental: (name, id, directive) => `${name} (document "${id}") uses @${directive}, which is not available over MCP: a tool returns one complete result. Fix: remove @${directive}, ${EXCLUDE}.`,
|
|
1254
|
+
description: (name, id) => `${name} (document "${id}") has no description: an agent picks a tool by its description. Fix: write one above the operation ("""Find a book by its id.""" query ${name} ...), or set operations.descriptions.${name}.`,
|
|
1255
|
+
reserved: (name, id, tool) => `${name} (document "${id}") gives the tool name ${tool}, and graphql_* names are the generic tools'. Fix: rename the operation, ${EXCLUDE}.`,
|
|
1256
|
+
duplicate: (tool, a, b) => `${a.name} (document "${a.id}") and ${b.name} (document "${b.id}") both give the tool name ${tool}. Fix: rename one of them, ${EXCLUDE}.`,
|
|
1257
|
+
tooLong: (name, id, tool) => `${name} (document "${id}") gives a tool name of ${tool.length} characters, and MCP allows ${MAX_TOOL_NAME}. Fix: rename the operation, ${EXCLUDE}.`,
|
|
1258
|
+
unusedDescription: (key, close) => `operations.descriptions.${key} matches no operation of operations.documents${close ? ` (there is ${close}: names are case-sensitive)` : ""}. Fix: ${close ? `rename the key to ${close}` : "remove the key, or name it after an operation of the manifest"}.`,
|
|
1259
|
+
empty: () => "genericTools is false and operations gives no tool: an agent would have nothing to call. Fix: check operations.documents and operations.include (mutations need mutations: true), or remove genericTools: false."
|
|
1260
|
+
};
|
|
1261
|
+
function operationsError(problems) {
|
|
1262
|
+
return new GraxiaConfigError3(`createMcp: operations has ${problems.length} problem${problems.length === 1 ? "" : "s"}:
|
|
1263
|
+
${problems.map((p) => `- ${p}`).join(`
|
|
1264
|
+
`)}`);
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// src/operations/build.ts
|
|
1268
|
+
function parsed(entry, build) {
|
|
1269
|
+
const { id, source } = entry;
|
|
1270
|
+
if (typeof source !== "string" || source.trim() === "") {
|
|
1271
|
+
build.problems.push(problem.source(id));
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
try {
|
|
1275
|
+
return { id, source, document: parse3(source) };
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1278
|
+
build.problems.push(problem.parse(entry.id, message));
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
function wanted(document, id, build) {
|
|
1283
|
+
const kept = [];
|
|
1284
|
+
for (const definition of document.definitions) {
|
|
1285
|
+
if (definition.kind !== Kind5.OPERATION_DEFINITION)
|
|
1286
|
+
continue;
|
|
1287
|
+
if (definition.name)
|
|
1288
|
+
build.names.add(definition.name.value);
|
|
1289
|
+
const kind = definition.operation;
|
|
1290
|
+
if (kind === "subscription")
|
|
1291
|
+
continue;
|
|
1292
|
+
if (kind === "mutation" && !build.mutations)
|
|
1293
|
+
continue;
|
|
1294
|
+
if (!definition.name) {
|
|
1295
|
+
build.problems.push(problem.anonymous(id));
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
const name = definition.name.value;
|
|
1299
|
+
if (build.options.include && !build.options.include({ name, kind, id }))
|
|
1300
|
+
continue;
|
|
1301
|
+
kept.push({ name, node: definition });
|
|
1302
|
+
}
|
|
1303
|
+
return kept;
|
|
1304
|
+
}
|
|
1305
|
+
function descriptionOf(wanted, build) {
|
|
1306
|
+
const given = build.options.descriptions;
|
|
1307
|
+
const own = given && Object.hasOwn(given, wanted.name) ? given[wanted.name] : undefined;
|
|
1308
|
+
return String(own ?? wanted.node.description?.value ?? "").trim();
|
|
1309
|
+
}
|
|
1310
|
+
function addTool(wanted, entry, build) {
|
|
1311
|
+
const { name: title, node: operation } = wanted;
|
|
1312
|
+
const { id, document } = entry;
|
|
1313
|
+
const name = toolNameOf(title);
|
|
1314
|
+
const description = descriptionOf(wanted, build);
|
|
1315
|
+
const before = build.problems.length;
|
|
1316
|
+
if (description === "")
|
|
1317
|
+
build.problems.push(problem.description(title, id));
|
|
1318
|
+
if (name.startsWith(RESERVED_PREFIX))
|
|
1319
|
+
build.problems.push(problem.reserved(title, id, name));
|
|
1320
|
+
if (name.length > MAX_TOOL_NAME)
|
|
1321
|
+
build.problems.push(problem.tooLong(title, id, name));
|
|
1322
|
+
const taken = build.tools.get(name);
|
|
1323
|
+
if (taken)
|
|
1324
|
+
build.problems.push(problem.duplicate(name, { name: taken.title, id: taken.id }, { name: title, id }));
|
|
1325
|
+
if (build.problems.length > before)
|
|
1326
|
+
return;
|
|
1327
|
+
build.tools.set(name, {
|
|
1328
|
+
name,
|
|
1329
|
+
title,
|
|
1330
|
+
description,
|
|
1331
|
+
kind: operation.operation === "mutation" ? "mutation" : "query",
|
|
1332
|
+
id,
|
|
1333
|
+
source: entry.source,
|
|
1334
|
+
document,
|
|
1335
|
+
inputSchema: inputSchemaOf(build.schema, document, operation),
|
|
1336
|
+
outputSchema: outputSchemaOf(build.schema, document, operation)
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
function addDocument(raw, build) {
|
|
1340
|
+
const entry = parsed(raw, build);
|
|
1341
|
+
if (!entry)
|
|
1342
|
+
return;
|
|
1343
|
+
const { document } = entry;
|
|
1344
|
+
const operations = wanted(document, entry.id, build);
|
|
1345
|
+
if (operations.length === 0)
|
|
1346
|
+
return;
|
|
1347
|
+
const names = operations.map((o) => o.name);
|
|
1348
|
+
const directive = incrementalDirective(document);
|
|
1349
|
+
if (directive) {
|
|
1350
|
+
build.problems.push(problem.incremental(names.join(", "), entry.id, directive));
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
const errors = validate2(build.schema, document, specifiedRules);
|
|
1354
|
+
if (errors.length > 0) {
|
|
1355
|
+
build.problems.push(problem.invalid(names, entry.id, errors.map((e) => e.message)));
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (validate2(build.schema, document, [NoSchemaIntrospectionCustomRule2]).length > 0) {
|
|
1359
|
+
build.problems.push(problem.introspection(names, entry.id));
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
for (const operation of operations)
|
|
1363
|
+
addTool(operation, entry, build);
|
|
1364
|
+
}
|
|
1365
|
+
function checkDescriptions(build) {
|
|
1366
|
+
for (const key of Object.keys(build.options.descriptions ?? {})) {
|
|
1367
|
+
if (build.names.has(key))
|
|
1368
|
+
continue;
|
|
1369
|
+
const close = [...build.names].find((name) => name.toLowerCase() === key.toLowerCase());
|
|
1370
|
+
build.problems.push(problem.unusedDescription(key, close));
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
function buildOperationTools(schema, options, mutations) {
|
|
1374
|
+
const build = {
|
|
1375
|
+
schema,
|
|
1376
|
+
options,
|
|
1377
|
+
mutations,
|
|
1378
|
+
problems: [],
|
|
1379
|
+
tools: new Map,
|
|
1380
|
+
names: new Set
|
|
1381
|
+
};
|
|
1382
|
+
const entries = manifestEntries(options?.documents);
|
|
1383
|
+
if (!entries)
|
|
1384
|
+
throw operationsError([problem.manifest()]);
|
|
1385
|
+
for (const entry of entries)
|
|
1386
|
+
addDocument(entry, build);
|
|
1387
|
+
checkDescriptions(build);
|
|
1388
|
+
if (build.problems.length > 0)
|
|
1389
|
+
throw operationsError(build.problems);
|
|
1390
|
+
return [...build.tools.values()];
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// src/operations/visible.ts
|
|
1394
|
+
import { validate as validate3 } from "graphql";
|
|
1395
|
+
function createVisibleTools(tools) {
|
|
1396
|
+
const cache = new WeakMap;
|
|
1397
|
+
return (view) => {
|
|
1398
|
+
let visible = cache.get(view);
|
|
1399
|
+
if (!visible) {
|
|
1400
|
+
visible = tools.filter((tool) => validate3(view.schema, tool.document, VIEW_RULES).length === 0);
|
|
1401
|
+
cache.set(view, visible);
|
|
1402
|
+
}
|
|
1403
|
+
return visible;
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
// src/toolset.ts
|
|
1408
|
+
function typedTools(graxia, options, mutations) {
|
|
1409
|
+
const generic = options.genericTools ?? true;
|
|
1410
|
+
if (!options.operations) {
|
|
1411
|
+
if (!generic)
|
|
1412
|
+
throw new GraxiaConfigError4("createMcp: genericTools is false and there is no operations: an agent would have nothing to call. Fix: pass operations: { documents: manifest }, or remove genericTools: false.");
|
|
1413
|
+
return [];
|
|
1414
|
+
}
|
|
1415
|
+
const typed = buildOperationTools(graxia.schema, options.operations, mutations);
|
|
1416
|
+
if (!generic && typed.length === 0)
|
|
1417
|
+
throw operationsError([problem.empty()]);
|
|
1418
|
+
return typed;
|
|
1419
|
+
}
|
|
1420
|
+
function createToolset(graxia, options, mutations, onError) {
|
|
1421
|
+
const typed = typedTools(graxia, options, mutations);
|
|
1422
|
+
const generic = options.genericTools === false ? "off" : graxia.trustedDocuments?.mode === "strict" ? "refused" : "on";
|
|
1423
|
+
if (generic === "refused" && typed.length === 0)
|
|
1424
|
+
onError(new GraxiaConfigError4("createMcp: graxia runs trusted documents in strict mode and `operations` gives no tool: agents can read the schema but run nothing. Fix: pass `operations: { documents }`."));
|
|
1425
|
+
const visible = createVisibleTools(typed);
|
|
1426
|
+
const writing = new Map(typed.filter((tool) => tool.kind === "mutation").map((t) => [t.name, t]));
|
|
1427
|
+
return {
|
|
1428
|
+
typed,
|
|
1429
|
+
generic,
|
|
1430
|
+
visible,
|
|
1431
|
+
async writes(name, view) {
|
|
1432
|
+
if (name === "graphql_mutate")
|
|
1433
|
+
return generic === "on";
|
|
1434
|
+
const tool = writing.get(name);
|
|
1435
|
+
if (!tool)
|
|
1436
|
+
return false;
|
|
1437
|
+
try {
|
|
1438
|
+
return visible(await view()).includes(tool);
|
|
1439
|
+
} catch {
|
|
1440
|
+
return false;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// src/view-cache.ts
|
|
1447
|
+
function createViewSource(schema, can) {
|
|
1448
|
+
let shared;
|
|
1449
|
+
const viewOf = async (request, serverContext, auth) => {
|
|
1450
|
+
if (can)
|
|
1451
|
+
return buildView(schema, await (auth ? can(request, serverContext, auth) : can(request, serverContext)));
|
|
1452
|
+
shared ??= buildView(schema);
|
|
1453
|
+
return shared;
|
|
1454
|
+
};
|
|
1455
|
+
return (request, serverContext, auth) => {
|
|
1456
|
+
let pending;
|
|
1457
|
+
return () => {
|
|
1458
|
+
pending ??= viewOf(request, serverContext, auth);
|
|
1459
|
+
return pending;
|
|
1460
|
+
};
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/create.ts
|
|
1465
|
+
function sinkOf(option) {
|
|
1466
|
+
if (option === false)
|
|
1467
|
+
return () => {};
|
|
1468
|
+
const sink = option ?? ((error) => {
|
|
1469
|
+
if (error instanceof Error && error.message.startsWith("Rejected "))
|
|
1470
|
+
return;
|
|
1471
|
+
console.error("[graxia/mcp] unexpected error", error);
|
|
1472
|
+
});
|
|
1473
|
+
return (error) => {
|
|
1474
|
+
try {
|
|
1475
|
+
sink(error);
|
|
1476
|
+
} catch {}
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
function createMcp(graxia, options) {
|
|
1480
|
+
checkOriginOptions(options.allowedHosts, options.allowedOrigins);
|
|
1481
|
+
const onError = sinkOf(options.onError);
|
|
1482
|
+
const settings = {
|
|
1483
|
+
allowedOrigins: options.allowedOrigins ?? [],
|
|
1484
|
+
allowedHosts: options.allowedHosts ?? defaultHosts(),
|
|
1485
|
+
maxBody: graxia.limits.bodyBytes
|
|
1486
|
+
};
|
|
1487
|
+
const auth = options.auth ? resolveAuth(options.auth) : undefined;
|
|
1488
|
+
const mutations = options.mutations ?? false;
|
|
1489
|
+
const carrier = createContextCarrier();
|
|
1490
|
+
const views = createViewSource(graxia.schema, options.can);
|
|
1491
|
+
const toolset = createToolset(graxia, options, mutations, onError);
|
|
1492
|
+
const handler = createMcpHandler(serverFactory({ graxia, options, auth, carrier, toolset, onError }), {
|
|
1493
|
+
maxRequestBodySize: settings.maxBody,
|
|
1494
|
+
onerror: (error) => onError(error)
|
|
1495
|
+
});
|
|
1496
|
+
return {
|
|
1497
|
+
metadataPath: auth?.metadataPath,
|
|
1498
|
+
metadata: metadataHandler(auth, mutations),
|
|
1499
|
+
async fetch(request, ...rest) {
|
|
1500
|
+
const cors = corsOrigin(request, settings.allowedOrigins);
|
|
1501
|
+
try {
|
|
1502
|
+
const admitted = await admit(request, settings, auth && ((r) => authenticate(r, auth, onError)));
|
|
1503
|
+
if (admitted instanceof Response)
|
|
1504
|
+
return withCors(admitted, cors);
|
|
1505
|
+
const principal = admitted.gated;
|
|
1506
|
+
const serverContext = rest[0] ?? {};
|
|
1507
|
+
const state = {
|
|
1508
|
+
serverContext,
|
|
1509
|
+
calls: await toolCallsOf(admitted.request),
|
|
1510
|
+
view: views(admitted.request, serverContext, principal)
|
|
1511
|
+
};
|
|
1512
|
+
if (auth && principal && mutations) {
|
|
1513
|
+
const stepUp = await writeStepUp(auth, principal, state.calls.called, (name) => toolset.writes(name, state.view));
|
|
1514
|
+
if (stepUp)
|
|
1515
|
+
return withCors(stepUp, cors);
|
|
1516
|
+
}
|
|
1517
|
+
const response = await carrier.run(state, () => runAs(principal, () => handler.fetch(admitted.request)));
|
|
1518
|
+
return withCors(response, cors);
|
|
1519
|
+
} catch (error) {
|
|
1520
|
+
onError(error);
|
|
1521
|
+
return withCors(refusal(500, "The MCP server failed to handle the request.", "Retry later; check the server logs."), cors);
|
|
1522
|
+
}
|
|
1523
|
+
},
|
|
1524
|
+
dispose: () => handler.close()
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
export {
|
|
1528
|
+
createMcp,
|
|
1529
|
+
mcpAuth
|
|
1530
|
+
};
|
|
1531
|
+
|
|
1532
|
+
//# debugId=FD985FEB20AF4DC164756E2164756E21
|
|
1533
|
+
//# sourceMappingURL=index.js.map
|