@lostgradient/backchannel-mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +47 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/operation-tools.d.ts +148 -0
- package/dist/operation-tools.js +356 -0
- package/dist/velveteen.d.ts +47 -0
- package/dist/velveteen.js +243 -0
- package/package.json +30 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024–2026 Steve Kinney
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Backchannel MCP
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An application that serves its own operation catalog through `createOperationHandler` can mount its `mcpExposable` operations as MCP tools with `createOperationMcpMount(options)`, on the 2026-07-28 and 2025-11-25 protocol lanes. Each such operation becomes a tool of its own name whose input schema is the operation's, and each call runs through the full catalog pipeline (transport `mcp`, access policy, parsing, `authorize`, output validation) as the principal the handler authenticated. A unary operation answers with its validated output as `structuredContent`; a `subscription` operation answers with the elements recorded after its `fromCursor`, up to `maxEvents` (default 100), and the cursor to resume from, so a client polls it instead of holding a stream; a catalog fault, a refused caller included, is a tool error result. The mount is stateless like `/mcp` and starts nothing the catalog does not.
|
|
4
|
+
|
|
5
|
+
Supply the host’s name and version in `serverInfo`. Other options include `pathPrefix` (default `/mcp`), `maxBodyBytes`, `maxEvents`, `idleMs` (how long a `subscription` tool waits for the next element, default 250 ms), and two for MCP Apps. `resources` injects `OperationMcpResource` entries (a `ui://` page, say) that the server lists and reads, each optionally narrowed per caller by `authorize`, so a caller it refuses finds the resource neither listed nor readable; the `resources` capability is advertised only when there is at least one. `toolMeta` attaches `_meta` to a tool's listing by operation name, such as the `ui.resourceUri` that links a tool to a page. The mount knows nothing of what a resource holds: the application builds the page and hands it in.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createOperationHandler, defineOperation } from '@lostgradient/backchannel';
|
|
9
|
+
import { createOperationMcpMount } from '@lostgradient/backchannel-mcp';
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
|
|
12
|
+
const echo = defineOperation({
|
|
13
|
+
name: 'probe.echo',
|
|
14
|
+
mcpExposable: true,
|
|
15
|
+
summary: 'Echo a message',
|
|
16
|
+
destructive: false,
|
|
17
|
+
inputSchema: z.object({ message: z.string() }),
|
|
18
|
+
outputSchema: z.object({ message: z.string() }),
|
|
19
|
+
access: { kind: 'public' },
|
|
20
|
+
transports: { http: false, jsonRpcHttp: true, jsonRpcWebSocket: false, jsonRpcStdio: false },
|
|
21
|
+
unknownKeyPolicy: { http: 'reject', jsonRpc: 'reject' },
|
|
22
|
+
invoke: async ({ input }) => ({ message: input.message }),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
export const handler = createOperationHandler({
|
|
26
|
+
operations: [echo],
|
|
27
|
+
host: {},
|
|
28
|
+
mounts: [
|
|
29
|
+
createOperationMcpMount({
|
|
30
|
+
serverInfo: { name: 'probe', title: 'Probe', version: '1.0.0' },
|
|
31
|
+
resources: [
|
|
32
|
+
{
|
|
33
|
+
uri: 'ui://probe/page',
|
|
34
|
+
name: 'probe-page',
|
|
35
|
+
mimeType: 'text/html;profile=mcp-app',
|
|
36
|
+
text: '<!doctype html><title>probe</title>',
|
|
37
|
+
_meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } },
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
toolMeta: { 'probe.echo': { ui: { resourceUri: 'ui://probe/page' } } },
|
|
41
|
+
}),
|
|
42
|
+
],
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The mount serves catalog tools and injected resources, including when its host runs on Cloudflare Workers. [`@lostgradient/bureau`](../bureau/README.md#mcp-adapter-cor-839-cor-910) is the consumer in this repository.
|
|
47
|
+
|
|
48
|
+
For a Velveteen application, `mountCatalog` from `@lostgradient/backchannel-mcp/velveteen` registers the catalog, MCP endpoint and discovery routes together. Supply `basePath`, `publicOrigin`, the catalog operations and host, the application's `authenticateApi` function, and `mcp.serverInfo` with an authorization profile. `externalOAuth` from `@lostgradient/mcp/oauth` accepts an issuer, token verifier and current-principal resolver; the resolver returns the Backchannel `principal` and its `delegableScopes`. `hostedOAuth` accepts the application's session callbacks, OAuth store, default scopes and descriptions, and configures its issuer when the catalog starts. The resource URL includes the application's base path; its protected-resource metadata is served at the public root. A missing grantable scope receives an OAuth challenge, while a permanent policy denial remains a catalog fault.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createOperationMcpMount, type OperationMcpMountOptions, type OperationMcpResource, } from "./operation-tools.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createOperationMcpMount, } from "./operation-tools.js";
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import type { OperationFault, OperationHandlerMount, OperationHandlerMountContext, OperationHandlerMountOperation } from '@lostgradient/backchannel';
|
|
2
|
+
/**
|
|
3
|
+
* Options for {@link createOperationMcpMount}.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import type { OperationMcpMountOptions } from '@lostgradient/backchannel-mcp';
|
|
8
|
+
*
|
|
9
|
+
* const options: OperationMcpMountOptions = { serverInfo: { name: 'probe', version: '1.0.0' }, pathPrefix: '/mcp', maxEvents: 50 };
|
|
10
|
+
* void options;
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export type OperationMcpMountOptions = {
|
|
14
|
+
/** Select tools visible to the current request's principal. */
|
|
15
|
+
readonly operationFilter?: (operation: OperationHandlerMountOperation, context: OperationHandlerMountContext) => boolean;
|
|
16
|
+
/** Return a Bearer challenge when the caller can grant a missing tool scope. */
|
|
17
|
+
readonly scopeChallenge?: (operation: OperationHandlerMountOperation, context: OperationHandlerMountContext, input: unknown, signal: AbortSignal) => Promise<{
|
|
18
|
+
challenge?: string;
|
|
19
|
+
fault?: OperationFault;
|
|
20
|
+
} | undefined>;
|
|
21
|
+
/** Declare that this mount accepts OAuth credentials for its catalog policies. */
|
|
22
|
+
readonly oauth?: boolean;
|
|
23
|
+
/** The path the mount owns on the operation handler. Defaults to `/mcp`. */
|
|
24
|
+
readonly pathPrefix?: string;
|
|
25
|
+
/** Upper bound on a POST body, answered `413` when exceeded. */
|
|
26
|
+
readonly maxBodyBytes?: number;
|
|
27
|
+
/** The server identity the MCP handshake reports. */
|
|
28
|
+
readonly serverInfo: {
|
|
29
|
+
/** The server's machine-readable name. */
|
|
30
|
+
readonly name: string;
|
|
31
|
+
/** The display name, when supplied. */
|
|
32
|
+
readonly title?: string;
|
|
33
|
+
/** The API version reported on the wire. */
|
|
34
|
+
readonly version: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The most elements one call to a `subscription` tool returns. The tool answers with what is
|
|
38
|
+
* recorded after its `fromCursor`, up to this many, and the cursor to resume from. Defaults to 100.
|
|
39
|
+
*/
|
|
40
|
+
readonly maxEvents?: number;
|
|
41
|
+
/**
|
|
42
|
+
* How long a `subscription` tool waits for the next element before it answers with what it has.
|
|
43
|
+
* A replayed history arrives back to back, so the first gap this long ends the call. Defaults to
|
|
44
|
+
* 250 milliseconds.
|
|
45
|
+
*/
|
|
46
|
+
readonly idleMs?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Resources the server serves through `resources/list` and `resources/read` (COR-910), such as an
|
|
49
|
+
* MCP App's `ui://` page. Injected at mount time, so the mount knows nothing of what they hold.
|
|
50
|
+
* Absent, the server advertises no `resources` capability.
|
|
51
|
+
*/
|
|
52
|
+
readonly resources?: readonly OperationMcpResource[];
|
|
53
|
+
/**
|
|
54
|
+
* Metadata attached to a tool's listing as its `_meta`, keyed by operation name, such as the
|
|
55
|
+
* `ui.resourceUri` that links a tool to an MCP App. An entry for an operation that is not served
|
|
56
|
+
* as a tool is ignored.
|
|
57
|
+
*/
|
|
58
|
+
readonly toolMeta?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
59
|
+
/**
|
|
60
|
+
* Metadata attached as `_meta` to every tool that has no `toolMeta` entry, such as the
|
|
61
|
+
* `ui.visibility` that keeps a tool from MCP App pages. An entry replaces it whole; the two are
|
|
62
|
+
* never merged. Absent, such a tool's listing carries no `_meta`.
|
|
63
|
+
*/
|
|
64
|
+
readonly defaultToolMeta?: Readonly<Record<string, unknown>>;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* One resource an {@link OperationMcpMountOptions.resources} option serves.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* import type { OperationMcpResource } from '@lostgradient/backchannel-mcp';
|
|
72
|
+
*
|
|
73
|
+
* const page: OperationMcpResource = {
|
|
74
|
+
* uri: 'ui://probe/page',
|
|
75
|
+
* name: 'probe-page',
|
|
76
|
+
* mimeType: 'text/html;profile=mcp-app',
|
|
77
|
+
* text: '<!doctype html><title>probe</title>',
|
|
78
|
+
* };
|
|
79
|
+
* void page;
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export type OperationMcpResource = {
|
|
83
|
+
/** The resource's URI; unique among the mount's resources. */
|
|
84
|
+
readonly uri: string;
|
|
85
|
+
/** The resource's name in a listing. */
|
|
86
|
+
readonly name: string;
|
|
87
|
+
/** The resource's display title. */
|
|
88
|
+
readonly title?: string;
|
|
89
|
+
/** A short description shown to clients. */
|
|
90
|
+
readonly description?: string;
|
|
91
|
+
/** The media type of the resource contents. */
|
|
92
|
+
readonly mimeType: string;
|
|
93
|
+
/** The contents. A function runs on every read, with the context of the request. */
|
|
94
|
+
readonly text: string | ((context: OperationHandlerMountContext) => string | Promise<string>);
|
|
95
|
+
/** Metadata for the resource's listing and its contents, such as an MCP App's `ui` declaration. */
|
|
96
|
+
readonly _meta?: Readonly<Record<string, unknown>>;
|
|
97
|
+
/**
|
|
98
|
+
* Whether the request's caller may see the resource. A caller it refuses finds the resource
|
|
99
|
+
* neither listed nor readable, as if it did not exist. Absent, every caller the mount serves may.
|
|
100
|
+
*/
|
|
101
|
+
readonly authorize?: (context: OperationHandlerMountContext) => boolean;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Serve a catalog's `mcpExposable` operations as MCP tools, mounted on
|
|
105
|
+
* `createOperationHandler` (COR-839). Each operation becomes a tool of its
|
|
106
|
+
* own name whose input schema is the operation's; a call runs through the full
|
|
107
|
+
* catalog pipeline (transport `mcp`, access policy, parsing, `authorize`,
|
|
108
|
+
* output validation) as the principal the handler authenticated, so the tool
|
|
109
|
+
* reaches nothing the caller could not reach on the catalog's other
|
|
110
|
+
* transports.
|
|
111
|
+
*
|
|
112
|
+
* Both MCP protocol eras are served: the 2026-07-28 revision on the SDK's
|
|
113
|
+
* modern lane and 2025-era clients on its stateless legacy lane. A unary
|
|
114
|
+
* operation answers with its validated output as `structuredContent`. A
|
|
115
|
+
* `subscription` operation answers with the elements recorded after its
|
|
116
|
+
* `fromCursor`, up to `maxEvents`, and the cursor to resume from, so a client
|
|
117
|
+
* polls it rather than holding a stream. Every catalog fault, a refused caller
|
|
118
|
+
* included, is a tool error result whose structured content is the fault.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* import { createOperationHandler, defineOperation } from '@lostgradient/backchannel';
|
|
123
|
+
* import { createOperationMcpMount } from '@lostgradient/backchannel-mcp';
|
|
124
|
+
* import { z } from 'zod';
|
|
125
|
+
*
|
|
126
|
+
* const echo = defineOperation({
|
|
127
|
+
* name: 'probe.echo',
|
|
128
|
+
* mcpExposable: true,
|
|
129
|
+
* summary: 'Echo a message',
|
|
130
|
+
* destructive: false,
|
|
131
|
+
* inputSchema: z.object({ message: z.string() }),
|
|
132
|
+
* outputSchema: z.object({ message: z.string() }),
|
|
133
|
+
* access: { kind: 'public' },
|
|
134
|
+
* transports: { http: false, jsonRpcHttp: true, jsonRpcWebSocket: false, jsonRpcStdio: false },
|
|
135
|
+
* unknownKeyPolicy: { http: 'reject', jsonRpc: 'reject' },
|
|
136
|
+
* invoke: async ({ input }) => ({ message: input.message }),
|
|
137
|
+
* });
|
|
138
|
+
*
|
|
139
|
+
* const handler = createOperationHandler({
|
|
140
|
+
* operations: [echo],
|
|
141
|
+
* host: {},
|
|
142
|
+
* mounts: [createOperationMcpMount({ serverInfo: { name: 'probe', version: '1.0.0' } })],
|
|
143
|
+
* });
|
|
144
|
+
* void handler;
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export declare function createOperationMcpMount(options: OperationMcpMountOptions): OperationHandlerMount;
|
|
148
|
+
export declare function isMcpTool(operation: OperationHandlerMountOperation): boolean;
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { createMcpHandler, fromJsonSchema, McpServer, } from '@modelcontextprotocol/server';
|
|
2
|
+
import { faultWireAdvice, isAuthenticated, zodToJsonSchema, } from '@lostgradient/backchannel/internals';
|
|
3
|
+
const DEFAULT_MCP_MAX_BODY_BYTES = 1_048_576;
|
|
4
|
+
const DEFAULT_MAX_EVENTS = 100;
|
|
5
|
+
const DEFAULT_IDLE_MS = 250;
|
|
6
|
+
const MAX_TOOL_RESULT_BYTES = 256 * 1024;
|
|
7
|
+
/** The key under `AuthInfo.extra` that carries the mount's context to the server factory. */
|
|
8
|
+
const CONTEXT_KEY = 'weftOperationMount';
|
|
9
|
+
/**
|
|
10
|
+
* Serve a catalog's `mcpExposable` operations as MCP tools, mounted on
|
|
11
|
+
* `createOperationHandler` (COR-839). Each operation becomes a tool of its
|
|
12
|
+
* own name whose input schema is the operation's; a call runs through the full
|
|
13
|
+
* catalog pipeline (transport `mcp`, access policy, parsing, `authorize`,
|
|
14
|
+
* output validation) as the principal the handler authenticated, so the tool
|
|
15
|
+
* reaches nothing the caller could not reach on the catalog's other
|
|
16
|
+
* transports.
|
|
17
|
+
*
|
|
18
|
+
* Both MCP protocol eras are served: the 2026-07-28 revision on the SDK's
|
|
19
|
+
* modern lane and 2025-era clients on its stateless legacy lane. A unary
|
|
20
|
+
* operation answers with its validated output as `structuredContent`. A
|
|
21
|
+
* `subscription` operation answers with the elements recorded after its
|
|
22
|
+
* `fromCursor`, up to `maxEvents`, and the cursor to resume from, so a client
|
|
23
|
+
* polls it rather than holding a stream. Every catalog fault, a refused caller
|
|
24
|
+
* included, is a tool error result whose structured content is the fault.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* import { createOperationHandler, defineOperation } from '@lostgradient/backchannel';
|
|
29
|
+
* import { createOperationMcpMount } from '@lostgradient/backchannel-mcp';
|
|
30
|
+
* import { z } from 'zod';
|
|
31
|
+
*
|
|
32
|
+
* const echo = defineOperation({
|
|
33
|
+
* name: 'probe.echo',
|
|
34
|
+
* mcpExposable: true,
|
|
35
|
+
* summary: 'Echo a message',
|
|
36
|
+
* destructive: false,
|
|
37
|
+
* inputSchema: z.object({ message: z.string() }),
|
|
38
|
+
* outputSchema: z.object({ message: z.string() }),
|
|
39
|
+
* access: { kind: 'public' },
|
|
40
|
+
* transports: { http: false, jsonRpcHttp: true, jsonRpcWebSocket: false, jsonRpcStdio: false },
|
|
41
|
+
* unknownKeyPolicy: { http: 'reject', jsonRpc: 'reject' },
|
|
42
|
+
* invoke: async ({ input }) => ({ message: input.message }),
|
|
43
|
+
* });
|
|
44
|
+
*
|
|
45
|
+
* const handler = createOperationHandler({
|
|
46
|
+
* operations: [echo],
|
|
47
|
+
* host: {},
|
|
48
|
+
* mounts: [createOperationMcpMount({ serverInfo: { name: 'probe', version: '1.0.0' } })],
|
|
49
|
+
* });
|
|
50
|
+
* void handler;
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export function createOperationMcpMount(options) {
|
|
54
|
+
const limits = collectionLimits(options);
|
|
55
|
+
const { name, title, version } = options.serverInfo;
|
|
56
|
+
const serverInfo = { name, ...(title === undefined ? {} : { title }), version };
|
|
57
|
+
const resources = validatedResources(options.resources ?? []);
|
|
58
|
+
const { operationFilter, scopeChallenge } = options;
|
|
59
|
+
const toolMeta = options.toolMeta ?? {};
|
|
60
|
+
const metaOf = (operationName) => toolMetaOf(toolMeta, options.defaultToolMeta, operationName);
|
|
61
|
+
const handler = createMcpHandler((request) => buildServer(contextOf(request), serverInfo, limits, resources, metaOf, options.oauth === true, scopeChallenge, operationFilter), {
|
|
62
|
+
legacy: 'stateless',
|
|
63
|
+
maxRequestBodySize: options.maxBodyBytes ?? DEFAULT_MCP_MAX_BODY_BYTES,
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
pathPrefix: options.pathPrefix ?? '/mcp',
|
|
67
|
+
fetch: (request, context) => handler.fetch(request, { authInfo: authInfoFor(context) }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function collectionLimits(options) {
|
|
71
|
+
const maxEvents = options.maxEvents ?? DEFAULT_MAX_EVENTS;
|
|
72
|
+
if (!Number.isInteger(maxEvents) || maxEvents < 1) {
|
|
73
|
+
throw new RangeError('createOperationMcpMount: maxEvents must be a positive integer');
|
|
74
|
+
}
|
|
75
|
+
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
76
|
+
if (!Number.isFinite(idleMs) || idleMs < 0) {
|
|
77
|
+
throw new RangeError('createOperationMcpMount: idleMs must be a non-negative number');
|
|
78
|
+
}
|
|
79
|
+
return { maxEvents, idleMs };
|
|
80
|
+
}
|
|
81
|
+
function validatedResources(resources) {
|
|
82
|
+
const seen = new Set();
|
|
83
|
+
for (const resource of resources) {
|
|
84
|
+
if (resource.uri === '' || resource.name === '' || resource.mimeType === '') {
|
|
85
|
+
throw new RangeError('createOperationMcpMount: a resource needs a uri, a name, and a mimeType');
|
|
86
|
+
}
|
|
87
|
+
if (seen.has(resource.uri)) {
|
|
88
|
+
throw new RangeError(`createOperationMcpMount: resource "${resource.uri}" is declared twice`);
|
|
89
|
+
}
|
|
90
|
+
seen.add(resource.uri);
|
|
91
|
+
}
|
|
92
|
+
return [...resources];
|
|
93
|
+
}
|
|
94
|
+
function authInfoFor(context) {
|
|
95
|
+
const { principal } = context;
|
|
96
|
+
const authenticated = isAuthenticated(principal);
|
|
97
|
+
return {
|
|
98
|
+
token: '',
|
|
99
|
+
clientId: authenticated ? (principal.subject ?? principal.method) : 'anonymous',
|
|
100
|
+
scopes: authenticated ? [...principal.scopes] : [],
|
|
101
|
+
extra: { [CONTEXT_KEY]: context },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function contextOf(request) {
|
|
105
|
+
const context = request.authInfo?.extra?.[CONTEXT_KEY];
|
|
106
|
+
// The mount's own `fetch` attaches it; the SDK never builds a server for a request without it.
|
|
107
|
+
if (context === undefined)
|
|
108
|
+
throw new Error('createOperationMcpMount: request carries no context');
|
|
109
|
+
return context;
|
|
110
|
+
}
|
|
111
|
+
/** Register the injected resources the request's caller may see. */
|
|
112
|
+
function registerResources(server, context, resources) {
|
|
113
|
+
for (const resource of resources) {
|
|
114
|
+
if (resource.authorize !== undefined && !resource.authorize(context))
|
|
115
|
+
continue;
|
|
116
|
+
server.registerResource(resource.name, resource.uri, {
|
|
117
|
+
...(resource.title === undefined ? {} : { title: resource.title }),
|
|
118
|
+
...(resource.description === undefined ? {} : { description: resource.description }),
|
|
119
|
+
mimeType: resource.mimeType,
|
|
120
|
+
...(resource._meta === undefined ? {} : { _meta: { ...resource._meta } }),
|
|
121
|
+
}, async (uri) => ({
|
|
122
|
+
contents: [
|
|
123
|
+
{
|
|
124
|
+
uri: uri.href,
|
|
125
|
+
mimeType: resource.mimeType,
|
|
126
|
+
text: typeof resource.text === 'string' ? resource.text : await resource.text(context),
|
|
127
|
+
...(resource._meta === undefined ? {} : { _meta: { ...resource._meta } }),
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
}));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function buildServer(context, serverInfo, limits, resources, metaOf, oauth, scopeChallenge, operationFilter) {
|
|
134
|
+
const server = new McpServer(serverInfo, {
|
|
135
|
+
capabilities: resources.length === 0 ? { tools: {} } : { tools: {}, resources: {} },
|
|
136
|
+
});
|
|
137
|
+
registerResources(server, context, resources);
|
|
138
|
+
for (const operation of context.operations) {
|
|
139
|
+
if (!isMcpTool(operation) ||
|
|
140
|
+
(operationFilter !== undefined && !operationFilter(operation, context)))
|
|
141
|
+
continue;
|
|
142
|
+
const outputSchema = operation.kind === 'subscription'
|
|
143
|
+
? undefined
|
|
144
|
+
: objectOutputSchema(zodToJsonSchema(operation.outputSchema, 'output'));
|
|
145
|
+
if (operation.kind === 'stream' ||
|
|
146
|
+
(operation.kind !== 'subscription' && outputSchema === undefined))
|
|
147
|
+
continue;
|
|
148
|
+
server.registerTool(operation.name, {
|
|
149
|
+
title: operation.summary,
|
|
150
|
+
description: operation.description ?? operation.summary,
|
|
151
|
+
inputSchema: fromJsonSchema(toolInputSchema(operation)),
|
|
152
|
+
...(outputSchema === undefined
|
|
153
|
+
? {}
|
|
154
|
+
: { outputSchema: fromJsonSchema(outputSchema) }),
|
|
155
|
+
annotations: {
|
|
156
|
+
readOnlyHint: !operation.destructive &&
|
|
157
|
+
(operation.kind === 'subscription' || operation.behavior?.kind === 'read'),
|
|
158
|
+
destructiveHint: operation.destructive,
|
|
159
|
+
},
|
|
160
|
+
...toolMetadata(metaOf(operation.name)._meta, operation, oauth),
|
|
161
|
+
}, async (input, handlerContext) => {
|
|
162
|
+
const refusal = await scopeChallenge?.(operation, context, input, handlerContext.mcpReq.signal);
|
|
163
|
+
if (refusal !== undefined) {
|
|
164
|
+
return {
|
|
165
|
+
...faultResult(refusal.fault ?? {
|
|
166
|
+
code: 'Forbidden',
|
|
167
|
+
message: 'Insufficient scope',
|
|
168
|
+
data: { reason: 'insufficient scope' },
|
|
169
|
+
}),
|
|
170
|
+
...(refusal.challenge === undefined
|
|
171
|
+
? {}
|
|
172
|
+
: { _meta: { 'mcp/www_authenticate': [refusal.challenge] } }),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
return operation.kind === 'subscription'
|
|
176
|
+
? collectSubscription(context, operation.name, input, limits, handlerContext.mcpReq.signal)
|
|
177
|
+
: handlerContext.mcpReq.signal.aborted
|
|
178
|
+
? faultResult({
|
|
179
|
+
code: 'Unprocessable',
|
|
180
|
+
message: 'call cancelled',
|
|
181
|
+
data: { reason: 'cancelled' },
|
|
182
|
+
})
|
|
183
|
+
: toolResult(await context.dispatch(operation.name, input, {
|
|
184
|
+
transport: 'mcp',
|
|
185
|
+
signal: handlerContext.mcpReq.signal,
|
|
186
|
+
}));
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return server;
|
|
190
|
+
}
|
|
191
|
+
export function isMcpTool(operation) {
|
|
192
|
+
if (!operation.mcpExposable || operation.mcpTool !== undefined || operation.kind === 'stream')
|
|
193
|
+
return false;
|
|
194
|
+
return (operation.kind === 'subscription' ||
|
|
195
|
+
objectOutputSchema(zodToJsonSchema(operation.outputSchema, 'output')) !== undefined);
|
|
196
|
+
}
|
|
197
|
+
function objectOutputSchema(schema) {
|
|
198
|
+
if (schema['type'] === 'object')
|
|
199
|
+
return schema;
|
|
200
|
+
if (schema['type'] !== undefined)
|
|
201
|
+
return undefined;
|
|
202
|
+
const arms = schema['oneOf'] ?? schema['anyOf'];
|
|
203
|
+
if (!Array.isArray(arms) ||
|
|
204
|
+
arms.length === 0 ||
|
|
205
|
+
!arms.every((arm) => isRecord(arm) && objectOutputSchema(arm) !== undefined))
|
|
206
|
+
return undefined;
|
|
207
|
+
return { ...schema, type: 'object' };
|
|
208
|
+
}
|
|
209
|
+
function toolMetadata(meta, operation, oauth) {
|
|
210
|
+
const schemes = oauth && operation.parameterizedAccess === undefined
|
|
211
|
+
? securitySchemes(operation.access)
|
|
212
|
+
: undefined;
|
|
213
|
+
if (meta === undefined && schemes === undefined)
|
|
214
|
+
return {};
|
|
215
|
+
return { _meta: { ...meta, ...(schemes === undefined ? {} : { securitySchemes: schemes }) } };
|
|
216
|
+
}
|
|
217
|
+
function securitySchemes(access) {
|
|
218
|
+
const requirement = (value) => value.kind === 'allOf'
|
|
219
|
+
? [{ type: 'oauth2', scopes: [...value.scopes] }]
|
|
220
|
+
: value.scopes.map((scope) => ({ type: 'oauth2', scopes: [scope] }));
|
|
221
|
+
switch (access.kind) {
|
|
222
|
+
case 'public':
|
|
223
|
+
return [{ type: 'noauth' }];
|
|
224
|
+
case 'authenticated':
|
|
225
|
+
return [{ type: 'oauth2', scopes: [] }];
|
|
226
|
+
case 'scoped':
|
|
227
|
+
return requirement(access.scopes);
|
|
228
|
+
case 'scopedAlternatives':
|
|
229
|
+
return access.alternatives.flatMap(requirement);
|
|
230
|
+
case 'optionalAuth':
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** The operation's input schema, closed or open as its JSON-RPC unknown-key policy says. */
|
|
235
|
+
function toolInputSchema(operation) {
|
|
236
|
+
const schema = zodToJsonSchema(operation.inputSchema);
|
|
237
|
+
const { $schema: _unused, ...rest } = schema;
|
|
238
|
+
return { ...rest, additionalProperties: operation.unknownKeyPolicy.jsonRpc !== 'reject' };
|
|
239
|
+
}
|
|
240
|
+
function toolResult(result) {
|
|
241
|
+
if (!result.ok)
|
|
242
|
+
return faultResult(result.fault);
|
|
243
|
+
if (!isRecord(result.value))
|
|
244
|
+
return faultResult({
|
|
245
|
+
code: 'Unprocessable',
|
|
246
|
+
message: 'unsupported tool result',
|
|
247
|
+
data: { reason: 'not an object' },
|
|
248
|
+
});
|
|
249
|
+
let serialized;
|
|
250
|
+
try {
|
|
251
|
+
serialized = JSON.stringify(result.value);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return faultResult({
|
|
255
|
+
code: 'Unprocessable',
|
|
256
|
+
message: 'unsupported tool result',
|
|
257
|
+
data: { reason: 'not JSON serializable' },
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
if (new TextEncoder().encode(serialized).byteLength > MAX_TOOL_RESULT_BYTES)
|
|
261
|
+
return faultResult({
|
|
262
|
+
code: 'Unprocessable',
|
|
263
|
+
message: 'tool result exceeds 262144 bytes',
|
|
264
|
+
data: { reason: 'result too large' },
|
|
265
|
+
});
|
|
266
|
+
return {
|
|
267
|
+
content: [{ type: 'text', text: serialized }],
|
|
268
|
+
structuredContent: result.value,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* A fault is the tool's error result, carrying the catalog's fault (`code`, `message`, `data`) as
|
|
273
|
+
* structured content the model reads and can act on, with the same `retryable` (always) and
|
|
274
|
+
* `remediation` (when set) the REST and JSON-RPC envelopes carry. A refused caller is one too: the
|
|
275
|
+
* SDK answers any `tools/call` handler failure as an error result, so a refusal is the
|
|
276
|
+
* `Unauthorized` or `Forbidden` fault, as every other catalog transport names it.
|
|
277
|
+
*/
|
|
278
|
+
function faultResult(fault) {
|
|
279
|
+
const { retryable, remediation } = faultWireAdvice(fault);
|
|
280
|
+
const payload = {
|
|
281
|
+
code: fault.code,
|
|
282
|
+
message: fault.message,
|
|
283
|
+
...('data' in fault ? { data: fault.data } : {}),
|
|
284
|
+
retryable,
|
|
285
|
+
...(remediation === undefined ? {} : { remediation }),
|
|
286
|
+
};
|
|
287
|
+
let serialized;
|
|
288
|
+
try {
|
|
289
|
+
serialized = JSON.stringify(payload);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return { content: [{ type: 'text', text: 'Fault could not be serialized' }], isError: true };
|
|
293
|
+
}
|
|
294
|
+
if (new TextEncoder().encode(serialized).byteLength > MAX_TOOL_RESULT_BYTES) {
|
|
295
|
+
return {
|
|
296
|
+
content: [{ type: 'text', text: 'Fault exceeds the tool result limit' }],
|
|
297
|
+
isError: true,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
content: [{ type: 'text', text: serialized }],
|
|
302
|
+
structuredContent: payload,
|
|
303
|
+
isError: true,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Run a `subscription` operation and collect what it has already recorded: elements until none
|
|
308
|
+
* arrives for `idleMs`, at most `maxEvents`, then close it. The client resumes from `nextCursor`.
|
|
309
|
+
*/
|
|
310
|
+
async function collectSubscription(context, operationName, input, limits, signal) {
|
|
311
|
+
const started = await context.subscribe(operationName, input, { transport: 'mcp', signal });
|
|
312
|
+
if (!started.ok)
|
|
313
|
+
return faultResult(started.fault);
|
|
314
|
+
const { envelope, iterable, close } = started.value;
|
|
315
|
+
const events = [];
|
|
316
|
+
let ended = false;
|
|
317
|
+
const iterator = iterable[Symbol.asyncIterator]();
|
|
318
|
+
try {
|
|
319
|
+
while (events.length < limits.maxEvents && !signal.aborted) {
|
|
320
|
+
const next = await nextOrIdle(iterator, limits.idleMs);
|
|
321
|
+
if (next === 'idle')
|
|
322
|
+
break;
|
|
323
|
+
if (next.done === true) {
|
|
324
|
+
ended = true;
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
events.push(next.value);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
await close();
|
|
332
|
+
}
|
|
333
|
+
const last = events.at(-1);
|
|
334
|
+
const nextCursor = isRecord(last) && typeof last['cursor'] === 'string' ? last['cursor'] : null;
|
|
335
|
+
const value = { envelope, events, nextCursor, ended };
|
|
336
|
+
return toolResult({ ok: true, value });
|
|
337
|
+
}
|
|
338
|
+
async function nextOrIdle(iterator, idleMs) {
|
|
339
|
+
let timer;
|
|
340
|
+
const idle = new Promise((resolve) => {
|
|
341
|
+
timer = setTimeout(() => resolve('idle'), idleMs);
|
|
342
|
+
});
|
|
343
|
+
try {
|
|
344
|
+
return await Promise.race([iterator.next(), idle]);
|
|
345
|
+
}
|
|
346
|
+
finally {
|
|
347
|
+
clearTimeout(timer);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function isRecord(value) {
|
|
351
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
352
|
+
}
|
|
353
|
+
function toolMetaOf(toolMeta, defaultToolMeta, name) {
|
|
354
|
+
const meta = Object.hasOwn(toolMeta, name) ? toolMeta[name] : defaultToolMeta;
|
|
355
|
+
return meta === undefined ? {} : { _meta: { ...meta } };
|
|
356
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type AuthenticatedPrincipal, type OperationHandlerOptions } from '@lostgradient/backchannel';
|
|
2
|
+
import { type VerifiedGrant } from '@lostgradient/mcp/http';
|
|
3
|
+
import { type OperationMcpMountOptions } from "./operation-tools.js";
|
|
4
|
+
/** The verified connector grant and the application's current authority for it. */
|
|
5
|
+
export type CatalogAuthority = {
|
|
6
|
+
/** The authorization server advertised to MCP clients. */
|
|
7
|
+
issuer: string;
|
|
8
|
+
/** Verify a bearer credential and return its resource-bound grant. */
|
|
9
|
+
verifyAccessToken(token: string): Promise<VerifiedGrant | null>;
|
|
10
|
+
/** Resolve the subject's current principal and delegable permissions. */
|
|
11
|
+
resolvePrincipal(grant: VerifiedGrant): Promise<{
|
|
12
|
+
principal: AuthenticatedPrincipal;
|
|
13
|
+
delegableScopes: readonly string[];
|
|
14
|
+
} | null>;
|
|
15
|
+
/** Serve issuer routes when the application hosts its own authorization server. */
|
|
16
|
+
handle?(request: Request): Promise<Response>;
|
|
17
|
+
/** Subscribe to a grant's revocation while a response remains open. */
|
|
18
|
+
subscribeGrantRevocation?(grantId: string, listener: () => void): () => void;
|
|
19
|
+
};
|
|
20
|
+
type CatalogOptions<Host> = Pick<OperationHandlerOptions<Host>, 'operations' | 'host'> & {
|
|
21
|
+
basePath: string;
|
|
22
|
+
publicOrigin: string;
|
|
23
|
+
authenticateApi: NonNullable<OperationHandlerOptions<Host>['authenticate']>;
|
|
24
|
+
mcp: {
|
|
25
|
+
serverInfo: OperationMcpMountOptions['serverInfo'];
|
|
26
|
+
authorization: CatalogAuthority | {
|
|
27
|
+
configure(options: {
|
|
28
|
+
origin: string;
|
|
29
|
+
resourcePath: string;
|
|
30
|
+
scopes: string[];
|
|
31
|
+
}): CatalogAuthority;
|
|
32
|
+
};
|
|
33
|
+
requiredScopes?: readonly string[];
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
/** Register one catalog service and its protected discovery routes with Velveteen. */
|
|
37
|
+
export declare function mountCatalog<Host>(options: CatalogOptions<Host>): {
|
|
38
|
+
[options.basePath]: {
|
|
39
|
+
machineFormPaths(): string[];
|
|
40
|
+
rootPaths(base: string): string[];
|
|
41
|
+
start(base: string): {
|
|
42
|
+
fetch: (request: Request) => Promise<Response>;
|
|
43
|
+
close: () => void;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { createOperationHandler, createOperationRegistry, } from '@lostgradient/backchannel';
|
|
2
|
+
import { createProtectedHttpHandler } from '@lostgradient/mcp/http';
|
|
3
|
+
import { createOperationMcpMount, isMcpTool, } from "./operation-tools.js";
|
|
4
|
+
function alternatives(access) {
|
|
5
|
+
const requirements = access.kind === 'scoped'
|
|
6
|
+
? [access.scopes]
|
|
7
|
+
: access.kind === 'scopedAlternatives'
|
|
8
|
+
? access.alternatives
|
|
9
|
+
: access.kind === 'optionalAuth'
|
|
10
|
+
? [access.authenticatedScopes]
|
|
11
|
+
: [];
|
|
12
|
+
return requirements.flatMap((requirement) => requirement.kind === 'allOf'
|
|
13
|
+
? [[...requirement.scopes]]
|
|
14
|
+
: requirement.scopes.map((scope) => [scope]));
|
|
15
|
+
}
|
|
16
|
+
function canonicalPath(path) {
|
|
17
|
+
if (path !== '' && !/^\/(?:[^/?#\\]+)(?:\/[^/?#\\]+)*$/.test(path))
|
|
18
|
+
throw new TypeError('Invalid catalog mount path');
|
|
19
|
+
return path
|
|
20
|
+
.split('/')
|
|
21
|
+
.map((segment) => {
|
|
22
|
+
if (!segment)
|
|
23
|
+
return '';
|
|
24
|
+
const decoded = decodeURIComponent(segment);
|
|
25
|
+
if (!decoded || decoded === '.' || decoded === '..' || /[\\/]/.test(decoded))
|
|
26
|
+
throw new TypeError('Invalid catalog mount path');
|
|
27
|
+
return encodeURIComponent(decoded);
|
|
28
|
+
})
|
|
29
|
+
.join('/');
|
|
30
|
+
}
|
|
31
|
+
/** Register one catalog service and its protected discovery routes with Velveteen. */
|
|
32
|
+
export function mountCatalog(options) {
|
|
33
|
+
const suppliedProfile = options.mcp.authorization;
|
|
34
|
+
const capturedProfile = 'configure' in suppliedProfile
|
|
35
|
+
? { configure: suppliedProfile.configure.bind(suppliedProfile) }
|
|
36
|
+
: {
|
|
37
|
+
issuer: suppliedProfile.issuer,
|
|
38
|
+
verifyAccessToken: suppliedProfile.verifyAccessToken.bind(suppliedProfile),
|
|
39
|
+
resolvePrincipal: suppliedProfile.resolvePrincipal.bind(suppliedProfile),
|
|
40
|
+
...(suppliedProfile.handle === undefined
|
|
41
|
+
? {}
|
|
42
|
+
: { handle: suppliedProfile.handle.bind(suppliedProfile) }),
|
|
43
|
+
...(suppliedProfile.subscribeGrantRevocation === undefined
|
|
44
|
+
? {}
|
|
45
|
+
: {
|
|
46
|
+
subscribeGrantRevocation: suppliedProfile.subscribeGrantRevocation.bind(suppliedProfile),
|
|
47
|
+
}),
|
|
48
|
+
};
|
|
49
|
+
options = {
|
|
50
|
+
...options,
|
|
51
|
+
basePath: canonicalPath(options.basePath),
|
|
52
|
+
operations: options.operations.map((operation) => ({
|
|
53
|
+
...operation,
|
|
54
|
+
access: structuredClone(operation.access),
|
|
55
|
+
transports: { ...operation.transports },
|
|
56
|
+
unknownKeyPolicy: { ...operation.unknownKeyPolicy },
|
|
57
|
+
...(operation.behavior === undefined
|
|
58
|
+
? {}
|
|
59
|
+
: { behavior: structuredClone(operation.behavior) }),
|
|
60
|
+
...(operation.parameterizedAccess === undefined
|
|
61
|
+
? {}
|
|
62
|
+
: { parameterizedAccess: structuredClone(operation.parameterizedAccess) }),
|
|
63
|
+
...(operation.tags === undefined ? {} : { tags: [...operation.tags] }),
|
|
64
|
+
...(operation.conflictReasonTokens === undefined
|
|
65
|
+
? {}
|
|
66
|
+
: { conflictReasonTokens: [...operation.conflictReasonTokens] }),
|
|
67
|
+
...(operation.mcpTool === undefined ? {} : { mcpTool: { ...operation.mcpTool } }),
|
|
68
|
+
...(operation.producibleFaults === undefined
|
|
69
|
+
? {}
|
|
70
|
+
: { producibleFaults: [...operation.producibleFaults] }),
|
|
71
|
+
})),
|
|
72
|
+
mcp: {
|
|
73
|
+
...options.mcp,
|
|
74
|
+
authorization: capturedProfile,
|
|
75
|
+
serverInfo: { ...options.mcp.serverInfo },
|
|
76
|
+
...(options.mcp.requiredScopes === undefined
|
|
77
|
+
? {}
|
|
78
|
+
: { requiredScopes: [...options.mcp.requiredScopes] }),
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
const profile = options.mcp.authorization;
|
|
82
|
+
const policyRegistry = createOperationRegistry(options.operations);
|
|
83
|
+
const scopes = [
|
|
84
|
+
...new Set(options.operations.flatMap((operation) => isMcpTool(operation) ? alternatives(operation.access).flat() : [])),
|
|
85
|
+
];
|
|
86
|
+
const api = createOperationHandler({
|
|
87
|
+
host: options.host,
|
|
88
|
+
operations: options.operations,
|
|
89
|
+
authenticate: options.authenticateApi,
|
|
90
|
+
});
|
|
91
|
+
const issuerPath = new URL('configure' in profile ? options.publicOrigin : profile.issuer).pathname.replace(/\/$/, '');
|
|
92
|
+
return {
|
|
93
|
+
[options.basePath]: {
|
|
94
|
+
machineFormPaths() {
|
|
95
|
+
return 'configure' in profile || profile.handle
|
|
96
|
+
? [`${issuerPath}/oauth/token`, `${issuerPath}/oauth/revoke`]
|
|
97
|
+
: [];
|
|
98
|
+
},
|
|
99
|
+
rootPaths(base) {
|
|
100
|
+
const resourcePath = `${canonicalPath(base)}${options.basePath}/mcp`;
|
|
101
|
+
return [
|
|
102
|
+
`/.well-known/oauth-protected-resource${resourcePath}`,
|
|
103
|
+
...('configure' in profile || profile.handle
|
|
104
|
+
? [
|
|
105
|
+
`/.well-known/oauth-authorization-server${issuerPath}`,
|
|
106
|
+
...['authorize', 'token', 'register', 'revoke'].map((path) => `${issuerPath}/oauth/${path}`),
|
|
107
|
+
]
|
|
108
|
+
: []),
|
|
109
|
+
];
|
|
110
|
+
},
|
|
111
|
+
start(base) {
|
|
112
|
+
const resourcePath = `${canonicalPath(base)}${options.basePath}/mcp`;
|
|
113
|
+
const authorization = 'configure' in profile
|
|
114
|
+
? profile.configure({ origin: options.publicOrigin, resourcePath, scopes })
|
|
115
|
+
: profile;
|
|
116
|
+
const metadataPath = `/.well-known/oauth-protected-resource${resourcePath}`;
|
|
117
|
+
const protectedHttp = createProtectedHttpHandler({
|
|
118
|
+
origin: options.publicOrigin,
|
|
119
|
+
resourcePath,
|
|
120
|
+
issuer: authorization.issuer,
|
|
121
|
+
scopes,
|
|
122
|
+
verifyAccessToken: (token) => authorization.verifyAccessToken(token),
|
|
123
|
+
resolvePrincipal: (grant) => authorization.resolvePrincipal(grant),
|
|
124
|
+
...(authorization.subscribeGrantRevocation === undefined
|
|
125
|
+
? {}
|
|
126
|
+
: {
|
|
127
|
+
subscribeGrantRevocation: (grantId, listener) => authorization.subscribeGrantRevocation(grantId, listener),
|
|
128
|
+
}),
|
|
129
|
+
async dispatch(request, context) {
|
|
130
|
+
const admission = await context.requireScopes(options.mcp.requiredScopes ?? []);
|
|
131
|
+
if (!admission.ok)
|
|
132
|
+
return admission.response;
|
|
133
|
+
const headers = new Headers(request.headers);
|
|
134
|
+
headers.delete('authorization');
|
|
135
|
+
const url = new URL(request.url);
|
|
136
|
+
url.pathname = '/mcp';
|
|
137
|
+
const principal = admission.principal.principal;
|
|
138
|
+
const effectiveScopes = new Set(context.grant.scopes.filter((scope) => admission.principal.delegableScopes.includes(scope) &&
|
|
139
|
+
principal.scopes.has(scope)));
|
|
140
|
+
const effectivePrincipal = {
|
|
141
|
+
...principal,
|
|
142
|
+
scopes: effectiveScopes,
|
|
143
|
+
hasScope: (scope) => effectiveScopes.has(scope),
|
|
144
|
+
};
|
|
145
|
+
const handler = createOperationHandler({
|
|
146
|
+
host: options.host,
|
|
147
|
+
operations: options.operations,
|
|
148
|
+
authenticate: async () => ({
|
|
149
|
+
method: effectivePrincipal.method === 'jwt' ? 'jwt' : 'api-key',
|
|
150
|
+
principal: effectivePrincipal,
|
|
151
|
+
}),
|
|
152
|
+
mounts: [
|
|
153
|
+
createOperationMcpMount({
|
|
154
|
+
oauth: true,
|
|
155
|
+
serverInfo: options.mcp.serverInfo,
|
|
156
|
+
async scopeChallenge(operation, _context, input, signal) {
|
|
157
|
+
const latest = await context.requireScopes([]);
|
|
158
|
+
if (!latest.ok)
|
|
159
|
+
return {};
|
|
160
|
+
const currentPrincipal = latest.principal.principal;
|
|
161
|
+
const candidates = alternatives(operation.access);
|
|
162
|
+
const grantable = candidates.filter((candidate) => candidate.every((scope) => latest.principal.delegableScopes.includes(scope) &&
|
|
163
|
+
currentPrincipal.scopes.has(scope)));
|
|
164
|
+
const choice = grantable.find((candidate) => candidate.every((scope) => context.grant.scopes.includes(scope))) ?? grantable[0];
|
|
165
|
+
if (choice && choice.some((scope) => !context.grant.scopes.includes(scope))) {
|
|
166
|
+
const policy = options.operations.find((candidate) => candidate.name === operation.name);
|
|
167
|
+
if (!policy?.checkPolicy)
|
|
168
|
+
return {
|
|
169
|
+
fault: {
|
|
170
|
+
code: 'Forbidden',
|
|
171
|
+
message: 'Permission denied',
|
|
172
|
+
data: { reason: 'Policy cannot be checked' },
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
const decision = await policy.checkPolicy(input, {
|
|
176
|
+
principal: currentPrincipal,
|
|
177
|
+
host: options.host,
|
|
178
|
+
transport: 'mcp',
|
|
179
|
+
registry: policyRegistry,
|
|
180
|
+
signal,
|
|
181
|
+
});
|
|
182
|
+
if (!decision.ok)
|
|
183
|
+
return { fault: decision.fault };
|
|
184
|
+
}
|
|
185
|
+
const result = await context.requireScopes(choice ?? []);
|
|
186
|
+
if (result.ok) {
|
|
187
|
+
const fresh = result.principal.principal;
|
|
188
|
+
const effective = new Set(context.grant.scopes.filter((scope) => result.principal.delegableScopes.includes(scope) &&
|
|
189
|
+
fresh.scopes.has(scope)));
|
|
190
|
+
Object.assign(effectivePrincipal, fresh, {
|
|
191
|
+
scopes: effective,
|
|
192
|
+
hasScope: (scope) => effective.has(scope),
|
|
193
|
+
});
|
|
194
|
+
if (fresh.workspace === undefined)
|
|
195
|
+
delete effectivePrincipal.workspace;
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
const challenge = result.response.headers.get('www-authenticate');
|
|
199
|
+
return challenge
|
|
200
|
+
? {
|
|
201
|
+
challenge: `${challenge}, error_description="Additional permission is required"`,
|
|
202
|
+
}
|
|
203
|
+
: {};
|
|
204
|
+
},
|
|
205
|
+
}),
|
|
206
|
+
],
|
|
207
|
+
});
|
|
208
|
+
return handler(new Request(url, {
|
|
209
|
+
method: request.method,
|
|
210
|
+
headers,
|
|
211
|
+
body: request.body,
|
|
212
|
+
signal: request.signal,
|
|
213
|
+
duplex: 'half',
|
|
214
|
+
}));
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
let closed = false;
|
|
218
|
+
const fetch = async (request) => {
|
|
219
|
+
if (closed)
|
|
220
|
+
return new Response('Catalog disposed', { status: 503 });
|
|
221
|
+
const url = new URL(request.url);
|
|
222
|
+
if (url.pathname === metadataPath)
|
|
223
|
+
return protectedHttp(request);
|
|
224
|
+
if (url.pathname === '/mcp') {
|
|
225
|
+
url.pathname = resourcePath;
|
|
226
|
+
return protectedHttp(new Request(url, request));
|
|
227
|
+
}
|
|
228
|
+
if (authorization.handle &&
|
|
229
|
+
(url.pathname.startsWith('/.well-known/') ||
|
|
230
|
+
url.pathname.startsWith(`${issuerPath}/oauth/`)))
|
|
231
|
+
return authorization.handle(request);
|
|
232
|
+
return api(request);
|
|
233
|
+
};
|
|
234
|
+
return {
|
|
235
|
+
fetch,
|
|
236
|
+
close: () => {
|
|
237
|
+
closed = true;
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lostgradient/backchannel-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The stateless HTTP MCP mount for Backchannel operation catalogs.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/stevekinney/corvidae.git",
|
|
11
|
+
"directory": "packages/backchannel-mcp"
|
|
12
|
+
},
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22",
|
|
15
|
+
"bun": ">=1.4.0"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./velveteen": {
|
|
23
|
+
"types": "./dist/velveteen.d.ts",
|
|
24
|
+
"default": "./dist/velveteen.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@lostgradient/backchannel": "0.1.0",
|
|
29
|
+
"@lostgradient/mcp": "0.3.0",
|
|
30
|
+
"@modelcontextprotocol/server": "^2.4.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {}
|
|
6
33
|
}
|