@substrat-run/vertical-host 0.224.0 → 0.226.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/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -4
- package/dist/index.js.map +1 -1
- package/dist/mcp-search.d.ts +96 -0
- package/dist/mcp-search.d.ts.map +1 -0
- package/dist/mcp-search.js +207 -0
- package/dist/mcp-search.js.map +1 -0
- package/dist/mcp.d.ts +19 -0
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +305 -215
- package/dist/mcp.js.map +1 -1
- package/dist/operations-routes.d.ts.map +1 -1
- package/dist/operations-routes.js +10 -4
- package/dist/operations-routes.js.map +1 -1
- package/package.json +7 -7
package/dist/mcp.js
CHANGED
|
@@ -85,6 +85,7 @@ import { classifyError, messageOf, problemResponse } from './errors.js';
|
|
|
85
85
|
import { observeOutputFields, outputWalkOf } from './field-coverage.js';
|
|
86
86
|
import { assertDistinctToolNames, assertMcpPathFree, bearerClaims, carriesAct } from './mcp-guard.js';
|
|
87
87
|
import { liftImages } from './mcp-images.js';
|
|
88
|
+
import { keywordToolIndex, MCP_SEARCH_LIMIT_DEFAULT, MCP_SEARCH_LIMIT_MAX, MCP_SEARCH_QUERY_MAX, MCP_SEARCH_TOOL, searchMatchOf, } from './mcp-search.js';
|
|
88
89
|
/**
|
|
89
90
|
* The protocol revisions this server speaks, newest first.
|
|
90
91
|
*
|
|
@@ -120,13 +121,13 @@ export function mcpToolName(operation) {
|
|
|
120
121
|
* (`{ shape?: … }`) and several suites pass a plain object, which is legal there and
|
|
121
122
|
* unconvertible here; a permissive schema is the honest answer for both.
|
|
122
123
|
*/
|
|
123
|
-
function jsonSchemaOf(schema) {
|
|
124
|
+
function jsonSchemaOf(schema, io = 'input') {
|
|
124
125
|
// Zod 4 marks its own with `_zod`. Checked before converting because
|
|
125
126
|
// `z.toJSONSchema` throws on anything else rather than returning a result.
|
|
126
127
|
if (!schema?._zod)
|
|
127
128
|
return { type: 'object', properties: {} };
|
|
128
129
|
try {
|
|
129
|
-
const { $schema: _drop, ...rest } = z.toJSONSchema(schema, { io
|
|
130
|
+
const { $schema: _drop, ...rest } = z.toJSONSchema(schema, { io, target: 'draft-2020-12' });
|
|
130
131
|
return rest;
|
|
131
132
|
}
|
|
132
133
|
catch {
|
|
@@ -293,6 +294,27 @@ export function mcpToolsOf(operations) {
|
|
|
293
294
|
}
|
|
294
295
|
return tools;
|
|
295
296
|
}
|
|
297
|
+
/**
|
|
298
|
+
* The JSON Schema of what a tool answers, for `search`'s output signature (#3705), or `undefined`
|
|
299
|
+
* when the operation declares no output the mount can read. A paged read's declared `output` is
|
|
300
|
+
* the ENTRY, so its answer is spelled as the page the mount serves around it.
|
|
301
|
+
*/
|
|
302
|
+
function answerSchemaOf(op) {
|
|
303
|
+
if (!op.output?._zod)
|
|
304
|
+
return undefined;
|
|
305
|
+
const declared = jsonSchemaOf(op.output, 'output');
|
|
306
|
+
if (!op.paged)
|
|
307
|
+
return declared;
|
|
308
|
+
return {
|
|
309
|
+
type: 'object',
|
|
310
|
+
properties: {
|
|
311
|
+
entries: { type: 'array', items: declared },
|
|
312
|
+
nextCursor: { type: ['string', 'null'] },
|
|
313
|
+
...(op.paged.total ? { total: { type: 'integer' } } : {}),
|
|
314
|
+
},
|
|
315
|
+
required: ['entries', 'nextCursor', ...(op.paged.total ? ['total'] : [])],
|
|
316
|
+
};
|
|
317
|
+
}
|
|
296
318
|
/**
|
|
297
319
|
* A server name, derived rather than declared.
|
|
298
320
|
*
|
|
@@ -316,6 +338,10 @@ function serverNameOf(tools) {
|
|
|
316
338
|
}
|
|
317
339
|
return best;
|
|
318
340
|
}
|
|
341
|
+
/** RFC 9728 inserts a resource's path into the well-known URL: `/.well-known/oauth-protected-resource/api/mcp`. */
|
|
342
|
+
const wellKnownOf = (path) => `/.well-known/oauth-protected-resource${path}`;
|
|
343
|
+
/** The code-mode endpoint's default path, beside the MCP endpoint: `/api/mcp` → `/api/mcp/code` (#3705). */
|
|
344
|
+
export const codeEndpointPath = (mcpPath) => `${mcpPath}/code`;
|
|
319
345
|
const rpcResult = (id, result) => ({ jsonrpc: '2.0', id, result });
|
|
320
346
|
const rpcError = (id, code, message, data) => ({
|
|
321
347
|
jsonrpc: '2.0',
|
|
@@ -471,18 +497,23 @@ function ceilingRefusal(ceiling, tool) {
|
|
|
471
497
|
* Presentation, never authorization: a call to a hidden tool is still answered by its own checks,
|
|
472
498
|
* exactly as before. So a stub that cannot answer (a vertical's own, or a read that fails) is shown
|
|
473
499
|
* the whole list rather than an empty one, and the failure is logged.
|
|
500
|
+
*
|
|
501
|
+
* `search` (#3705) promises more: a caller never learns that an operation exists unless they could
|
|
502
|
+
* call it. It asks with `unknown: 'keyless'`, so a stub that cannot answer shows only the tools no
|
|
503
|
+
* single key guards, and no keyed tool at all.
|
|
474
504
|
*/
|
|
475
|
-
async function visibleTools(tools, stub, ceiling) {
|
|
505
|
+
async function visibleTools(tools, stub, ceiling, unknown = 'all') {
|
|
476
506
|
const reachable = ceiling === undefined ? tools : tools.filter((t) => ceilingRefusal(ceiling, t) === null);
|
|
507
|
+
const keyless = () => reachable.filter((t) => t.permission === undefined);
|
|
477
508
|
if (!stub.heldPermissions)
|
|
478
|
-
return reachable;
|
|
509
|
+
return unknown === 'all' ? reachable : keyless();
|
|
479
510
|
let held;
|
|
480
511
|
try {
|
|
481
512
|
held = new Set(await stub.heldPermissions());
|
|
482
513
|
}
|
|
483
514
|
catch (err) {
|
|
484
|
-
console.error(JSON.stringify({ host: 'mcp-tools-unfiltered', code: errorCodeOf(err) ?? (err instanceof Error ? err.name : typeof err) }));
|
|
485
|
-
return reachable;
|
|
515
|
+
console.error(JSON.stringify({ host: unknown === 'all' ? 'mcp-tools-unfiltered' : 'mcp-search-keyless', code: errorCodeOf(err) ?? (err instanceof Error ? err.name : typeof err) }));
|
|
516
|
+
return unknown === 'all' ? reachable : keyless();
|
|
486
517
|
}
|
|
487
518
|
return reachable.filter((t) => t.permission === undefined || held.has(t.permission));
|
|
488
519
|
}
|
|
@@ -540,12 +571,17 @@ function statusOf(err) {
|
|
|
540
571
|
export function mountMcp(
|
|
541
572
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
542
573
|
app, operations, resolveStub, options = {}) {
|
|
543
|
-
//
|
|
574
|
+
// Every refusal comes before anything is registered, named for this mount.
|
|
544
575
|
assertDistinctToolNames(operations, mcpToolName, 'mountMcp');
|
|
545
576
|
const tools = mcpToolsOf(operations);
|
|
546
577
|
const path = options.path ?? mcpEndpointPath(options.basePath);
|
|
547
578
|
assertMcpPathFree(app, path, 'mountMcp');
|
|
548
|
-
const
|
|
579
|
+
const codePath = options.code ? (options.code.path ?? codeEndpointPath(path)) : undefined;
|
|
580
|
+
if (codePath !== undefined) {
|
|
581
|
+
if (codePath === path)
|
|
582
|
+
throw new Error(`mountMcp: the code-mode endpoint cannot share ${path} with the MCP endpoint`);
|
|
583
|
+
assertMcpPathFree(app, codePath, 'mountMcp');
|
|
584
|
+
}
|
|
549
585
|
const byName = new Map(tools.map((t) => [t.name, t]));
|
|
550
586
|
const serverInfo = {
|
|
551
587
|
name: options.serverInfo?.name ?? serverNameOf(tools),
|
|
@@ -687,7 +723,11 @@ app, operations, resolveStub, options = {}) {
|
|
|
687
723
|
return rpcResult(id, toolError(seen ? seen.message : messageOf(err)));
|
|
688
724
|
}
|
|
689
725
|
};
|
|
690
|
-
|
|
726
|
+
/**
|
|
727
|
+
* One endpoint's JSON-RPC dispatch: the handshake and `ping` are the same on both, and each
|
|
728
|
+
* endpoint brings its own tool list and tool call.
|
|
729
|
+
*/
|
|
730
|
+
const handlerFor = (listTools, callTool) => async (msg, stub, invocation, ceiling) => {
|
|
691
731
|
const id = msg.id ?? null;
|
|
692
732
|
const isNotification = msg.id === undefined;
|
|
693
733
|
switch (msg.method) {
|
|
@@ -710,23 +750,59 @@ app, operations, resolveStub, options = {}) {
|
|
|
710
750
|
return null;
|
|
711
751
|
case 'ping':
|
|
712
752
|
return isNotification ? null : rpcResult(id, {});
|
|
713
|
-
case 'tools/list':
|
|
714
|
-
|
|
715
|
-
return rpcResult(id, {
|
|
716
|
-
tools: visible.map((t) => ({
|
|
717
|
-
name: t.name,
|
|
718
|
-
description: t.description,
|
|
719
|
-
inputSchema: t.inputSchema,
|
|
720
|
-
annotations: t.annotations,
|
|
721
|
-
})),
|
|
722
|
-
});
|
|
723
|
-
}
|
|
753
|
+
case 'tools/list':
|
|
754
|
+
return rpcResult(id, { tools: await listTools(stub, ceiling) });
|
|
724
755
|
case 'tools/call':
|
|
725
|
-
return await
|
|
756
|
+
return await callTool(id, msg.params, stub, invocation, ceiling);
|
|
726
757
|
default:
|
|
727
758
|
return isNotification ? null : rpcError(id, -32601, `Method not found: ${msg.method ?? '(none)'}`);
|
|
728
759
|
}
|
|
729
760
|
};
|
|
761
|
+
const handle = handlerFor(async (stub, ceiling) => (await visibleTools(tools, stub, ceiling)).map((t) => ({
|
|
762
|
+
name: t.name,
|
|
763
|
+
description: t.description,
|
|
764
|
+
inputSchema: t.inputSchema,
|
|
765
|
+
annotations: t.annotations,
|
|
766
|
+
})), call);
|
|
767
|
+
/**
|
|
768
|
+
* The code-mode endpoint's dispatch (#3705): one tool, `search`, over the app's READS.
|
|
769
|
+
*
|
|
770
|
+
* A write is not indexed at all. The RFC exposes writes on this endpoint only where a deployment
|
|
771
|
+
* opts them in, and that is a later step, so today `search` can only ever point at a read. What
|
|
772
|
+
* the caller sees is decided by `visibleTools` before anything is ranked, failing closed (see
|
|
773
|
+
* there), so neither the ranking nor the count in the answer can say anything about an operation
|
|
774
|
+
* the caller could not call. Built when mounted, so a request pays for ranking alone.
|
|
775
|
+
*/
|
|
776
|
+
const codeHandler = () => {
|
|
777
|
+
const reads = tools.filter((t) => t.annotations.readOnlyHint);
|
|
778
|
+
const index = keywordToolIndex(reads);
|
|
779
|
+
const answers = new Map(reads.map((t) => [t.name, answerSchemaOf(operations[t.operation])]));
|
|
780
|
+
const search = async (id, params, stub, _invocation, ceiling) => {
|
|
781
|
+
const name = params?.['name'];
|
|
782
|
+
if (name !== MCP_SEARCH_TOOL.name)
|
|
783
|
+
return rpcError(id, -32602, `Unknown tool: ${typeof name === 'string' ? name : '(none)'}`);
|
|
784
|
+
const raw = params?.['arguments'];
|
|
785
|
+
const args = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
786
|
+
// Refused in-band, before anything is read: the agent reads what was wrong and asks again.
|
|
787
|
+
const unknownArgs = Object.keys(args).filter((k) => k !== 'query' && k !== 'limit');
|
|
788
|
+
if (unknownArgs.length > 0)
|
|
789
|
+
return rpcResult(id, toolError(`Unknown argument: ${unknownArgs.join(', ')}. search takes "query" and "limit".`));
|
|
790
|
+
const query = args['query'];
|
|
791
|
+
if (typeof query !== 'string' || query.length > MCP_SEARCH_QUERY_MAX) {
|
|
792
|
+
return rpcResult(id, toolError(`Invalid "query": expected text of at most ${MCP_SEARCH_QUERY_MAX} characters.`));
|
|
793
|
+
}
|
|
794
|
+
const limit = args['limit'] ?? MCP_SEARCH_LIMIT_DEFAULT;
|
|
795
|
+
if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > MCP_SEARCH_LIMIT_MAX) {
|
|
796
|
+
return rpcResult(id, toolError(`Invalid "limit": expected a whole number from 1 to ${MCP_SEARCH_LIMIT_MAX}. Above the maximum is refused, not capped.`));
|
|
797
|
+
}
|
|
798
|
+
const visible = await visibleTools(reads, stub, ceiling, 'keyless');
|
|
799
|
+
const ranked = index.rank(query, new Set(visible.map((t) => t.name)));
|
|
800
|
+
const results = ranked.slice(0, limit).map((t) => searchMatchOf(t, answers.get(t.name)));
|
|
801
|
+
// `total` is the count among what this caller may see, so a model knows whether to ask for more.
|
|
802
|
+
return rpcResult(id, { content: [{ type: 'text', text: JSON.stringify({ total: ranked.length, results }) }] });
|
|
803
|
+
};
|
|
804
|
+
return handlerFor(async () => [MCP_SEARCH_TOOL], search);
|
|
805
|
+
};
|
|
730
806
|
const pr = options.protectedResource ?? {
|
|
731
807
|
// Dispatch inside this app, never over the network. The ordinary auth route resolves
|
|
732
808
|
// the issuer from the same per-instance wiring as login. Preserve router assertions
|
|
@@ -753,211 +829,225 @@ app, operations, resolveStub, options = {}) {
|
|
|
753
829
|
},
|
|
754
830
|
};
|
|
755
831
|
/**
|
|
756
|
-
*
|
|
757
|
-
*
|
|
758
|
-
*
|
|
759
|
-
*
|
|
760
|
-
*
|
|
832
|
+
* Serve one endpoint at `path`: its RFC 9728 document, the `POST` that carries JSON-RPC, and the
|
|
833
|
+
* `405`s. Both endpoints (`/api/mcp`, and the code-mode one when asked for) go through this one
|
|
834
|
+
* function, so the audience check, the resolver's channel, the delegation ceiling and the request
|
|
835
|
+
* record are the same code for both. `root` also serves the pre-path-insertion document, which
|
|
836
|
+
* only `/api/mcp` answers.
|
|
761
837
|
*/
|
|
762
|
-
const
|
|
763
|
-
|
|
764
|
-
* The `WWW-Authenticate` challenge a 401 from this endpoint carries.
|
|
765
|
-
*
|
|
766
|
-
* Every default mount serves metadata, including one whose auth is not configured yet.
|
|
767
|
-
*/
|
|
768
|
-
const challengeFor = (c, ...params) => {
|
|
769
|
-
return `Bearer ${[`resource_metadata="${new URL(c.req.url).origin}${wellKnown}"`, ...params].join(', ')}`;
|
|
770
|
-
};
|
|
771
|
-
const document = async (c) => {
|
|
772
|
-
const servers = typeof pr.authorizationServers === 'function'
|
|
773
|
-
? await pr.authorizationServers(c)
|
|
774
|
-
: pr.authorizationServers;
|
|
775
|
-
c.header('Cache-Control', 'no-store');
|
|
776
|
-
return c.json({
|
|
777
|
-
resource: resourceFor(c),
|
|
778
|
-
// Omitted rather than empty when nothing is configured: a client reads an empty
|
|
779
|
-
// list as "this resource has no issuer", which is a different claim from "this
|
|
780
|
-
// install has not been configured yet" and sends it down a wrong path.
|
|
781
|
-
...(servers.length > 0 ? { authorization_servers: [...servers] } : {}),
|
|
782
|
-
bearer_methods_supported: ['header'],
|
|
783
|
-
...(pr.scopesSupported ? { scopes_supported: [...pr.scopesSupported] } : {}),
|
|
784
|
-
});
|
|
785
|
-
};
|
|
786
|
-
// RFC 9728 inserts the resource's path into the well-known URL, so a host serving
|
|
787
|
-
// several protected resources describes each one separately. The root form is
|
|
788
|
-
// served too, because clients that predate the path-insertion rule ask for it.
|
|
789
|
-
app.get(wellKnown, document);
|
|
790
|
-
app.get('/.well-known/oauth-protected-resource', document);
|
|
791
|
-
app.post(path, async (c) => {
|
|
792
|
-
const record = c.get?.(INVOCATION_RECORD_KEY)
|
|
793
|
-
?? invocationStampOf(c.req.raw)?.record;
|
|
794
|
-
let body;
|
|
795
|
-
try {
|
|
796
|
-
body = await c.req.json();
|
|
797
|
-
}
|
|
798
|
-
catch {
|
|
799
|
-
return c.json(rpcError(null, -32700, 'Parse error'), 400);
|
|
800
|
-
}
|
|
801
|
-
// Batching left the protocol in 2025-06-18 but earlier clients still send arrays,
|
|
802
|
-
// and answering one is cheaper than explaining why we will not.
|
|
803
|
-
const messages = Array.isArray(body) ? body : [body];
|
|
804
|
-
if (messages.length === 0)
|
|
805
|
-
return c.json(rpcError(null, -32600, 'Invalid Request'), 400);
|
|
838
|
+
const serve = (path, resource, handle, root) => {
|
|
839
|
+
const wellKnown = wellKnownOf(path);
|
|
806
840
|
/**
|
|
807
|
-
*
|
|
808
|
-
*
|
|
809
|
-
*
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
* **Except on `initialize`, where nothing has been negotiated yet** (#1711). The
|
|
814
|
-
* header there is a proposal, and the body's `protocolVersion` is the negotiation
|
|
815
|
-
* that answers it — with our own latest when we do not speak theirs. Refusing it
|
|
816
|
-
* here stopped every client newer than this list at a 400 before the resolver, so it
|
|
817
|
-
* never saw the 401 challenge that starts sign-in. The skip holds only when EVERY
|
|
818
|
-
* message is `initialize`, which dispatches nothing: a batch carrying any other
|
|
819
|
-
* message is judged by its pin as before. `notifications/initialized` is not
|
|
820
|
-
* included — the client sends it after reading our answer, pinned to what we said.
|
|
841
|
+
* This endpoint's resource identifier, as a client reached it. It is ONE computation for
|
|
842
|
+
* the three places that need it: the document below publishes it, a client requests a
|
|
843
|
+
* token for exactly that string, and the audience check holds the token to it. It is
|
|
844
|
+
* computed per request because a vertical answering on several hostnames is a different
|
|
845
|
+
* resource on each.
|
|
821
846
|
*/
|
|
822
|
-
const
|
|
823
|
-
const pinned = c.req.header(MCP_PROTOCOL_HEADER);
|
|
824
|
-
if (!handshakeOnly && pinned !== undefined && !MCP_PROTOCOL_VERSIONS.includes(pinned)) {
|
|
825
|
-
return c.json(rpcError(null, -32600, `Unsupported ${MCP_PROTOCOL_HEADER}: ${pinned}`, {
|
|
826
|
-
supported: [...MCP_PROTOCOL_VERSIONS],
|
|
827
|
-
}), 400);
|
|
828
|
-
}
|
|
847
|
+
const resourceFor = (c) => resource ?? mcpResourceOf(new URL(c.req.url).origin, path);
|
|
829
848
|
/**
|
|
830
|
-
*
|
|
831
|
-
*
|
|
832
|
-
*
|
|
833
|
-
* answer: the client holds a token, just not one for this endpoint, and the challenge
|
|
834
|
-
* it gets names the document that says which resource to ask for.
|
|
849
|
+
* The `WWW-Authenticate` challenge a 401 from this endpoint carries.
|
|
850
|
+
*
|
|
851
|
+
* Every default mount serves metadata, including one whose auth is not configured yet.
|
|
835
852
|
*/
|
|
836
|
-
const
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
return
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
853
|
+
const challengeFor = (c, ...params) => {
|
|
854
|
+
return `Bearer ${[`resource_metadata="${new URL(c.req.url).origin}${wellKnown}"`, ...params].join(', ')}`;
|
|
855
|
+
};
|
|
856
|
+
const document = async (c) => {
|
|
857
|
+
const servers = typeof pr.authorizationServers === 'function'
|
|
858
|
+
? await pr.authorizationServers(c)
|
|
859
|
+
: pr.authorizationServers;
|
|
860
|
+
c.header('Cache-Control', 'no-store');
|
|
861
|
+
return c.json({
|
|
862
|
+
resource: resourceFor(c),
|
|
863
|
+
// Omitted rather than empty when nothing is configured: a client reads an empty
|
|
864
|
+
// list as "this resource has no issuer", which is a different claim from "this
|
|
865
|
+
// install has not been configured yet" and sends it down a wrong path.
|
|
866
|
+
...(servers.length > 0 ? { authorization_servers: [...servers] } : {}),
|
|
867
|
+
bearer_methods_supported: ['header'],
|
|
868
|
+
...(pr.scopesSupported ? { scopes_supported: [...pr.scopesSupported] } : {}),
|
|
869
|
+
});
|
|
870
|
+
};
|
|
871
|
+
// RFC 9728 inserts the resource's path into the well-known URL, so a host serving
|
|
872
|
+
// several protected resources describes each one separately. The root form is
|
|
873
|
+
// served too, because clients that predate the path-insertion rule ask for it.
|
|
874
|
+
app.get(wellKnown, document);
|
|
875
|
+
if (root)
|
|
876
|
+
app.get('/.well-known/oauth-protected-resource', document);
|
|
877
|
+
app.post(path, async (c) => {
|
|
878
|
+
const record = c.get?.(INVOCATION_RECORD_KEY)
|
|
879
|
+
?? invocationStampOf(c.req.raw)?.record;
|
|
880
|
+
let body;
|
|
881
|
+
try {
|
|
882
|
+
body = await c.req.json();
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
return c.json(rpcError(null, -32700, 'Parse error'), 400);
|
|
886
|
+
}
|
|
887
|
+
// Batching left the protocol in 2025-06-18 but earlier clients still send arrays,
|
|
888
|
+
// and answering one is cheaper than explaining why we will not.
|
|
889
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
890
|
+
if (messages.length === 0)
|
|
891
|
+
return c.json(rpcError(null, -32600, 'Invalid Request'), 400);
|
|
848
892
|
/**
|
|
849
|
-
*
|
|
893
|
+
* A client pins the revision it negotiated on every later request. One we do not
|
|
894
|
+
* speak is a 400 BEFORE anything is dispatched: the alternative is answering a call
|
|
895
|
+
* under a contract we never agreed to, whose framing we would then be guessing at.
|
|
896
|
+
* Absent is not an error — a client that never sends it is the pre-header behaviour
|
|
897
|
+
* the transport still allows.
|
|
850
898
|
*
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
*
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
858
|
-
*
|
|
859
|
-
* this call alone — set as it starts, cleared as it returns, whatever it does.
|
|
899
|
+
* **Except on `initialize`, where nothing has been negotiated yet** (#1711). The
|
|
900
|
+
* header there is a proposal, and the body's `protocolVersion` is the negotiation
|
|
901
|
+
* that answers it — with our own latest when we do not speak theirs. Refusing it
|
|
902
|
+
* here stopped every client newer than this list at a 400 before the resolver, so it
|
|
903
|
+
* never saw the 401 challenge that starts sign-in. The skip holds only when EVERY
|
|
904
|
+
* message is `initialize`, which dispatches nothing: a batch carrying any other
|
|
905
|
+
* message is judged by its pin as before. `notifications/initialized` is not
|
|
906
|
+
* included — the client sends it after reading our answer, pinned to what we said.
|
|
860
907
|
*/
|
|
861
|
-
const
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
908
|
+
const handshakeOnly = messages.every((m) => !!m && typeof m === 'object' && m.method === 'initialize');
|
|
909
|
+
const pinned = c.req.header(MCP_PROTOCOL_HEADER);
|
|
910
|
+
if (!handshakeOnly && pinned !== undefined && !MCP_PROTOCOL_VERSIONS.includes(pinned)) {
|
|
911
|
+
return c.json(rpcError(null, -32600, `Unsupported ${MCP_PROTOCOL_HEADER}: ${pinned}`, {
|
|
912
|
+
supported: [...MCP_PROTOCOL_VERSIONS],
|
|
913
|
+
}), 400);
|
|
867
914
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
915
|
+
/**
|
|
916
|
+
* A token minted for some other audience is refused BEFORE the resolver, so a
|
|
917
|
+
* resolver that verifies only the signature and the issuer cannot let it through. See
|
|
918
|
+
* `audienceRefusal` for why this can only refuse. It is the RFC 6750 `invalid_token`
|
|
919
|
+
* answer: the client holds a token, just not one for this endpoint, and the challenge
|
|
920
|
+
* it gets names the document that says which resource to ask for.
|
|
921
|
+
*/
|
|
922
|
+
const refusal = audienceRefusal(c.req.header('authorization'), resourceFor(c));
|
|
923
|
+
if (refusal) {
|
|
924
|
+
recordAuthCheck({ stage: 'mcp-audience', outcome: 'refused', reason: 'resource-mismatch' });
|
|
925
|
+
if (record)
|
|
926
|
+
record.problemCode = 'unauthenticated';
|
|
927
|
+
const res = problemResponse(c, new HTTPException(401, { message: refusal }));
|
|
928
|
+
const challenged = new Response(res.body, res);
|
|
929
|
+
challenged.headers.set('WWW-Authenticate', challengeFor(c, 'error="invalid_token"', `error_description="${refusal}"`));
|
|
930
|
+
return challenged;
|
|
879
931
|
}
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
932
|
+
const replies = [];
|
|
933
|
+
try {
|
|
934
|
+
/**
|
|
935
|
+
* The whole ENDPOINT is authenticated, including `initialize`.
|
|
936
|
+
*
|
|
937
|
+
* Authenticating only the two methods that touch a scope would leave a client
|
|
938
|
+
* shaking hands anonymously and meeting the 401 mid-session, on its second
|
|
939
|
+
* request. Resolving here means the very first message a client sends is the one
|
|
940
|
+
* that fails, carrying the challenge — which is what makes discovery start on its
|
|
941
|
+
* own rather than after a false start. It is also the honest reading of the
|
|
942
|
+
* protocol: the resource is the endpoint, not a subset of its verbs.
|
|
943
|
+
*
|
|
944
|
+
* #1824: the channel a delegated token is admitted through (`mcpChannelOf`) exists for
|
|
945
|
+
* this call alone — set as it starts, cleared as it returns, whatever it does.
|
|
946
|
+
*/
|
|
947
|
+
const set = c.set.bind(c);
|
|
948
|
+
set(MCP_CHANNEL_KEY, { resource: resourceFor(c) });
|
|
949
|
+
let stub;
|
|
950
|
+
try {
|
|
951
|
+
stub = await resolveStub(c);
|
|
952
|
+
recordAuthCheck({ stage: 'mcp-caller', outcome: 'accepted', reason: 'caller-resolved' });
|
|
953
|
+
}
|
|
954
|
+
catch (error) {
|
|
955
|
+
const status = statusOf(error);
|
|
956
|
+
const refused = status === 401 || status === 403;
|
|
957
|
+
recordAuthCheck({ stage: 'mcp-caller', outcome: refused ? 'refused' : 'error', reason: refused ? 'caller-refused' : 'caller-error' });
|
|
958
|
+
const code = errorCodeOf(error) ?? (status === 401 ? 'unauthenticated' : status === 403 ? 'forbidden' : undefined);
|
|
959
|
+
if (record && code)
|
|
960
|
+
record.problemCode = code;
|
|
961
|
+
throw error;
|
|
962
|
+
}
|
|
963
|
+
finally {
|
|
964
|
+
set(MCP_CHANNEL_KEY, undefined);
|
|
965
|
+
}
|
|
966
|
+
// #1746/#1237: what `invocationLog` handed down, read defensively — a host without it
|
|
967
|
+
// simply records nothing.
|
|
968
|
+
const get = c.get;
|
|
969
|
+
const invocation = {
|
|
970
|
+
// #1893: or the platform's stamp, when the worker mounts no middleware.
|
|
971
|
+
record: get?.(INVOCATION_RECORD_KEY) ?? invocationStampOf(c.req.raw)?.record,
|
|
972
|
+
invocationId: requestIdOf(c),
|
|
973
|
+
// #1923: armed by the router for this request, decided when it was stamped.
|
|
974
|
+
fieldCoverage: fieldCoverageArmed(c.req.raw),
|
|
975
|
+
imageBudget: { used: 0 },
|
|
976
|
+
};
|
|
977
|
+
if (invocation.record && stub.subjectKind !== undefined)
|
|
978
|
+
invocation.record.principalKind = stub.subjectKind;
|
|
979
|
+
// #1824: after `resolveStub`, which is where a vertical hands its delegation over.
|
|
980
|
+
const ceiling = ceilingOf(c);
|
|
981
|
+
for (const msg of messages) {
|
|
982
|
+
if (!msg || typeof msg !== 'object') {
|
|
983
|
+
replies.push(rpcError(null, -32600, 'Invalid Request'));
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
const reply = await handle(msg, stub, invocation, ceiling);
|
|
987
|
+
if (reply)
|
|
988
|
+
replies.push(reply);
|
|
899
989
|
}
|
|
900
|
-
const reply = await handle(msg, stub, invocation, ceiling);
|
|
901
|
-
if (reply)
|
|
902
|
-
replies.push(reply);
|
|
903
990
|
}
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
return c.body
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
return
|
|
959
|
-
|
|
960
|
-
}
|
|
961
|
-
|
|
991
|
+
catch (err) {
|
|
992
|
+
// A 401 is the one failure that has somewhere to point, so it leaves here carrying
|
|
993
|
+
// the challenge that starts a client's authorization flow.
|
|
994
|
+
//
|
|
995
|
+
// **Returned, not thrown, and that distinction was a production bug.** The first
|
|
996
|
+
// version threw an `HTTPException` holding a prepared `res`, relying on
|
|
997
|
+
// `problemResponse` to hand it back untouched. In the workspace that works; in a
|
|
998
|
+
// PUSHED bundle it did not, because `err instanceof HTTPException` compares against
|
|
999
|
+
// whichever copy of `hono/http-exception` the bundler gave each package — two
|
|
1000
|
+
// copies, and the check is false for a genuine exception. The prepared response was
|
|
1001
|
+
// then discarded and the document rebuilt from an exception carrying no message,
|
|
1002
|
+
// which is exactly what production served: a 401 with an empty `detail` and no
|
|
1003
|
+
// challenge. A handler that already holds the response it wants should return it.
|
|
1004
|
+
if (statusOf(err) !== 401)
|
|
1005
|
+
throw err;
|
|
1006
|
+
// A refusal that already PREPARED a response keeps it, whole. That is the promise
|
|
1007
|
+
// `problemResponse` makes for every other route — "a redirect, a `WWW-Authenticate`
|
|
1008
|
+
// the route chose" — and a vertical whose `resolveStub` answers 401 with its own
|
|
1009
|
+
// challenge (a different realm, extra parameters) means the one it wrote. Read
|
|
1010
|
+
// structurally, for the same reason the status is: the exception may be the
|
|
1011
|
+
// bundle's second copy.
|
|
1012
|
+
//
|
|
1013
|
+
// Only a refusal that named NO challenge is normalised to this package's own
|
|
1014
|
+
// exception and rendered here, because `problemFor` cannot classify a foreign one
|
|
1015
|
+
// and would answer 400 for a refusal we have already established is a 401.
|
|
1016
|
+
// Re-wrapping keeps the message, so the document carries a real `detail` rather
|
|
1017
|
+
// than the empty one production served.
|
|
1018
|
+
const prepared = err?.res;
|
|
1019
|
+
const source = prepared instanceof Response
|
|
1020
|
+
? prepared
|
|
1021
|
+
: problemResponse(c, new HTTPException(401, { message: messageOf(err) }));
|
|
1022
|
+
if (source.headers.has('WWW-Authenticate'))
|
|
1023
|
+
return source;
|
|
1024
|
+
// Copied rather than mutated: a response that came back from `fetch` carries
|
|
1025
|
+
// immutable headers, and a route is free to have obtained one that way.
|
|
1026
|
+
const res = new Response(source.body, source);
|
|
1027
|
+
res.headers.set('WWW-Authenticate', challengeFor(c));
|
|
1028
|
+
return res;
|
|
1029
|
+
}
|
|
1030
|
+
// Nothing to answer means every message was a notification: 202, no body.
|
|
1031
|
+
if (replies.length === 0)
|
|
1032
|
+
return c.body(null, 202);
|
|
1033
|
+
return c.json(Array.isArray(body) ? replies : replies[0]);
|
|
1034
|
+
});
|
|
1035
|
+
// A 405 names the methods that are served (RFC 9110 §15.5.6): `POST` is the only one.
|
|
1036
|
+
const allow = { Allow: 'POST' };
|
|
1037
|
+
// No server-initiated stream, so no SSE to open. The transport allows saying so.
|
|
1038
|
+
app.get(path, (c) => c.json(rpcError(null, -32601, 'This server opens no event stream'), 405, allow));
|
|
1039
|
+
// #1824: and every other method is this mount's too — any verb a client sends, standard or
|
|
1040
|
+
// not — so a route registered after it can never answer here (see the header). `OPTIONS`
|
|
1041
|
+
// passes on, to a CORS middleware.
|
|
1042
|
+
app.all(path, async (c, next) => {
|
|
1043
|
+
if (c.req.method === 'OPTIONS')
|
|
1044
|
+
return next();
|
|
1045
|
+
return c.json(rpcError(null, -32601, 'Only POST is served here'), 405, allow);
|
|
1046
|
+
});
|
|
1047
|
+
};
|
|
1048
|
+
serve(path, pr.resource, handle, true);
|
|
1049
|
+
if (codePath !== undefined && options.code)
|
|
1050
|
+
serve(codePath, options.code.resource, codeHandler(), false);
|
|
1051
|
+
return { path, tools: tools.length, ...(codePath === undefined ? {} : { codePath }) };
|
|
962
1052
|
}
|
|
963
1053
|
//# sourceMappingURL=mcp.js.map
|