@ontrails/mcp 0.2.3 → 0.3.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/CHANGELOG.md +34 -0
- package/README.md +22 -2
- package/package.json +8 -3
- package/src/build.ts +85 -67
- package/src/fetch-boundary.ts +102 -0
- package/src/fetch.ts +86 -0
- package/src/index.ts +22 -6
- package/src/permit-resolution.ts +102 -0
- package/src/resource-access.ts +71 -0
- package/src/resources.ts +4 -0
- package/src/server.ts +317 -0
- package/src/stdio.ts +13 -15
- package/src/surface.ts +13 -264
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# @ontrails/mcp
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [`c2b11a4`](https://github.com/outfitter-dev/trails/commit/c2b11a4c5d61648471da1d9e919007b3d32960b3): Correct the default JSON-RPC `not_found` code from `-32601` (method not found) to `-32001`. Clients matching the previous numeric code must update or use the error category; HTTP status and CLI exit mappings are unchanged.
|
|
8
|
+
|
|
9
|
+
Export the shared JSON-RPC error data shape and public rendering helper from core, with a method-specific override for MCP `resources/read`. Unknown MCP resources retain protocol code `-32602` and now include `data.category`, `data.name`, and `data.retryable`. Trail failures remain `isError` tool results with shared metadata and public redaction.
|
|
10
|
+
- [`01361a6`](https://github.com/outfitter-dev/trails/commit/01361a6e1fca0c6445633e4428b973598a87b815): Network MCP surfaces never inherit a `createContext` permit. `deriveMcpTools` and the server options gain `credentialPosture`; `@ontrails/mcp/fetch` always builds on the `network` posture, where identity enters only through `resolvePermit`: a seeded `createContext` permit is discarded at runtime (one diagnostic names the migration) for tools and resource reads, `extra.permit` is ignored, a presented bearer with no resolver is an `AuthError` instead of absence, and a handler that exposes protected trails without a resolver is refused at build time with a `ValidationError` naming them. The stdio `host` posture is unchanged.
|
|
11
|
+
|
|
12
|
+
Migration: apps that seeded a permit through `createContext` on a network host move that credential into a verifier passed as `resolvePermit` (for example a JWKS or opaque adapter from `@ontrails/permits`) and keep `createContext` for the logger, extensions and resources it seeds. `--dev-permit` is not a migration path for network surfaces.
|
|
13
|
+
- [`76661d3`](https://github.com/outfitter-dev/trails/commit/76661d3b888295c3a515885f695677f0b7c2a3db): Pass raw Authorization and best-effort Bearer candidates to configured MCP permit policies without requiring a successful Bearer parse. Share request permit resolution internally while preserving trusted host permit precedence and unconfigured parser behavior. Configured policies must distinguish absent credentials from selected invalid credentials; metadata and tool arguments are not synthesized into headers.
|
|
14
|
+
- [`4b5d5bb`](https://github.com/outfitter-dev/trails/commit/4b5d5bb56639cbbec48c3072792f0ddc9deb2cb0): Add the portable `@ontrails/mcp/fetch` entry with a shared server factory for modern MCP and legacy stateless HTTP. Validate the authoritative request URL, optional Host authority and explicit HTTP(S) Origin allowlist before SDK dispatch. Forward actual request Authorization and per-request metadata to the existing permit resolver without synthesizing SDK auth information. Keep stdio imports outside the portable entry. HTTP challenge integration and real client interoperability retain separate acceptance gates.
|
|
15
|
+
- [`7c8d396`](https://github.com/outfitter-dev/trails/commit/7c8d396923495ab6758bc78f75332053c86e39ae): Resolve MCP tool permits from each request's bearer credential and application `_meta`, and remove `sessionId` from `ResolveMcpPermitInput` and `McpExtra`. Protocol sessions no longer supply permit inputs. Custom resolvers must remove session-derived state and trace identifiers; application state belongs in explicit handles in trail input/output schemas.
|
|
16
|
+
|
|
17
|
+
A configured resolver now runs even when no bearer token is present, allowing it to inspect untrusted metadata candidates or reject missing credentials according to the app's policy. Resolvers must handle absent bearer and metadata values and verify credentials before returning a permit. Explicit host-provided permits remain available for local stdio policy outside OAuth.
|
|
18
|
+
|
|
19
|
+
This establishes the MCP tool and stdio seam. The separately implemented fetch host must supply the same per-request context before fetch-path acceptance is complete.
|
|
20
|
+
- [`7868df9`](https://github.com/outfitter-dev/trails/commit/7868df908f310a4e3ad3e60e8bb1bc934d4e816a): Resolve permits for every MCP resource list and read request, and add `authorizeResourceRead` over the verified permit and canonical resource descriptor. Permission denials omit listed resources and reject direct reads; credential and operational failures remain terminal. Resolvers now receive resource requests, including requests without bearer credentials, and must return absence only when no accepted credential was selected. Resource policy preserves trusted local-host permits after absence and never after a verification error. This does not establish the separate fetch-shaped MCP host or private tool discovery.
|
|
21
|
+
- [`72274ce`](https://github.com/outfitter-dev/trails/commit/72274ce04d4f45eb69b70df2857f26f100fba195): Migrate MCP stdio serving to the official SDK v2 and its protocol-aware `serveStdio` entry. Replace the `@modelcontextprotocol/sdk` peer with `@modelcontextprotocol/server ^2.4.0`. `surface(graph)` remains the stdio one-liner and supports modern 2026-07-28 and legacy connections.
|
|
22
|
+
|
|
23
|
+
This is a documented 0.x break. Custom stdio hosts must change `await connectStdio(server)` to `const connection = await connectStdio(() => createServer(graph))` and close the returned connection handle. The factory must return a fresh server for SDK discovery and connection selection. Remove copied `transport: 'stdio'` properties; that documented option never existed.
|
|
24
|
+
|
|
25
|
+
Non-image blob results now emit valid embedded binary resources with nested `resource: { uri, mimeType, blob }` instead of invalid flat resource entries. Non-image streams are read and buffered into base64. Custom consumers must use the nested resource shape. Structured trail output descriptors are unchanged. MCP content types now follow the SDK's discriminated content shapes.
|
|
26
|
+
|
|
27
|
+
Session-permit API removal, the fetch-shaped handler, modern scalar/array output contract changes, and the temporary adopter migration skill have separate implementation gates.
|
|
28
|
+
|
|
29
|
+
## 0.2.5
|
|
30
|
+
|
|
31
|
+
No changes in this release.
|
|
32
|
+
|
|
33
|
+
## 0.2.4
|
|
34
|
+
|
|
35
|
+
No changes in this release.
|
|
36
|
+
|
|
3
37
|
## 0.2.3
|
|
4
38
|
|
|
5
39
|
No changes in this release.
|
package/README.md
CHANGED
|
@@ -48,6 +48,10 @@ for (const tool of result.value) {
|
|
|
48
48
|
|
|
49
49
|
`deriveMcpTools` returns `Result<McpToolDefinition[], Error>` rather than a bare array. It returns `Result.err(ValidationError)` if two trails derive the same MCP tool name. Each `McpToolDefinition` includes a `trailId` field that records which trail the tool was derived from.
|
|
50
50
|
|
|
51
|
+
## Portable HTTP Entry
|
|
52
|
+
|
|
53
|
+
Import `createFetchHandler` from `@ontrails/mcp/fetch` to obtain `{ fetch, close }` for Bun or Hono. The subpath avoids stdio imports and serves modern MCP plus legacy stateless HTTP. Hostnames default to loopback only; browser origins require an explicit exact HTTP(S) allowlist. Actual request Authorization and application metadata reach the existing permit resolver. See [MCP Over HTTP](../../docs/surfaces/mcp-http.md) for the Bun and Hono attachments, validation rules and the separate HTTP challenge and live-client follow-ups.
|
|
54
|
+
|
|
51
55
|
## API
|
|
52
56
|
|
|
53
57
|
| Export | What it does |
|
|
@@ -61,6 +65,20 @@ for (const tool of result.value) {
|
|
|
61
65
|
|
|
62
66
|
See the [API Reference](../../docs/api-reference.md) for the full list.
|
|
63
67
|
|
|
68
|
+
## Request credential resolution
|
|
69
|
+
|
|
70
|
+
A configured `resolvePermit` receives each request's raw `authorization`, best-effort `bearerToken` and untrusted application `_meta`. It owns the accepted credential source and syntax. An opaque key in Authorization can therefore reach that policy without first passing Bearer parsing. Metadata fields and tool arguments are never promoted into header credentials. HTTP header candidates require a real hosting adapter; the core does not synthesize them from `_meta`.
|
|
71
|
+
|
|
72
|
+
Return `Result.ok(null)` or `undefined` only when no accepted credential was selected. A selected malformed or invalid credential, lookup miss or operational failure must return an error; it stops even a public tool before host-context fallback or execution. Choose precedence before verification and never fall back to another candidate after selected failure. A Bearer-only policy must reject malformed presented Bearer credentials itself.
|
|
73
|
+
|
|
74
|
+
Two credential postures exist (`credentialPosture` on the derive and server options). On the `host` posture, which stdio uses, explicit host-provided `extra.permit` keeps its precedence and, when the configured resolver returns absence, trusted `createContext` permit configuration remains available as the launcher's own policy; a resolver error cannot use that fallback. On the `network` posture, which `@ontrails/mcp/fetch` always sets, identity enters only through `resolvePermit`: a `createContext` permit is discarded at runtime (one diagnostic names the migration), `extra.permit` is ignored, a presented bearer with no resolver is an `AuthError` rather than absence, and a surface that exposes protected trails without a resolver is refused at build time with a `ValidationError` listing the trails. Resolver absence means anonymous: public trails run, protected trails fail at enforcement.
|
|
75
|
+
|
|
76
|
+
Migration for apps that seeded a permit through `createContext` on a network host: move the credential into a verifier passed as `resolvePermit` (a JWKS or opaque adapter from `@ontrails/permits`), and keep `createContext` for the logger, extensions and resources it still seeds. `--dev-permit` is not a migration path for network surfaces.
|
|
77
|
+
|
|
78
|
+
Tool invocation and resource list/read requests share one internal request permit-resolution seam. Resource requests resolve once, then evaluate optional `authorizeResourceRead({ permit, resource })` policy against canonical catalog descriptors. Return `Result.ok()` to allow a URI or a `PermissionError` to deny it. Listing omits permission-denied URIs; direct reads reject them, and other errors fail the request. The descriptor carries a real `trailId` for trail-specific resources and none for aggregates. Without explicit read policy, the authored static resource population remains public.
|
|
79
|
+
|
|
80
|
+
Resolvers now receive resource requests even without bearer credentials. Every read rechecks; prior lists and other callers grant no authority. On the host posture, trusted `createContext` permits are available only after request-credential absence, never after verification failure; the network posture never consults them. Resource policy does not alter static tool discovery or redact the surface-map aggregate; deny unsafe aggregates when private member-level discovery is required. See [resource read policy](../../docs/surfaces/mcp.md#resource-read-policy) for configuration and migration guidance. This change does not establish Fetch hosting, query credentials, application-cookie policy or header extraction for a future host.
|
|
81
|
+
|
|
64
82
|
## Annotations
|
|
65
83
|
|
|
66
84
|
Trail intent, idempotency, and description map directly to MCP annotations:
|
|
@@ -141,8 +159,10 @@ await surface(graph, { exclude: ['internal.debug'] });
|
|
|
141
159
|
|
|
142
160
|
## Installation
|
|
143
161
|
|
|
144
|
-
|
|
162
|
+
The source targets the SDK v2 migration release, with `@modelcontextprotocol/server` 2.x (minimum 2.4.0) as its peer. Source support does not establish publication; use the Trails release containing this migration and its matching peer requirements.
|
|
145
163
|
|
|
146
164
|
```bash
|
|
147
|
-
bun add
|
|
165
|
+
bun add @ontrails/mcp '@modelcontextprotocol/server@^2.4.0'
|
|
148
166
|
```
|
|
167
|
+
|
|
168
|
+
See [SDK v2 Migration](../../docs/surfaces/mcp.md#sdk-v2-migration) for the stdio factory API and embedded binary content changes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ontrails/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/outfitter-dev/trails.git",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"type": "module",
|
|
18
18
|
"exports": {
|
|
19
19
|
".": "./src/index.ts",
|
|
20
|
+
"./fetch": "./src/fetch.ts",
|
|
20
21
|
"./package.json": "./package.json"
|
|
21
22
|
},
|
|
22
23
|
"scripts": {
|
|
@@ -27,10 +28,14 @@
|
|
|
27
28
|
"clean": "rm -rf dist *.tsbuildinfo"
|
|
28
29
|
},
|
|
29
30
|
"dependencies": {
|
|
30
|
-
"@ontrails/core": "^0.
|
|
31
|
+
"@ontrails/core": "^0.3.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
35
|
+
"hono": "^4.13.13"
|
|
31
36
|
},
|
|
32
37
|
"peerDependencies": {
|
|
33
|
-
"@modelcontextprotocol/
|
|
38
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
34
39
|
"zod": "^4.3.5"
|
|
35
40
|
}
|
|
36
41
|
}
|
package/src/build.ts
CHANGED
|
@@ -6,8 +6,12 @@
|
|
|
6
6
|
* Results to MCP responses.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import type {
|
|
10
|
+
EmbeddedResource,
|
|
11
|
+
ImageContent,
|
|
12
|
+
TextContent,
|
|
13
|
+
} from '@modelcontextprotocol/server';
|
|
9
14
|
import {
|
|
10
|
-
AuthError,
|
|
11
15
|
InternalError,
|
|
12
16
|
Result,
|
|
13
17
|
ValidationError,
|
|
@@ -49,6 +53,10 @@ import type {
|
|
|
49
53
|
|
|
50
54
|
import type { McpAnnotations } from './annotations.js';
|
|
51
55
|
import { deriveAnnotations } from './annotations.js';
|
|
56
|
+
import {
|
|
57
|
+
resolveMcpPermit,
|
|
58
|
+
surfaceContextFactory,
|
|
59
|
+
} from './permit-resolution.js';
|
|
52
60
|
import { createMcpProgressCallback } from './progress.js';
|
|
53
61
|
import { deriveToolName } from './tool-name.js';
|
|
54
62
|
|
|
@@ -129,8 +137,24 @@ export interface DeriveMcpToolsOptions extends BaseSurfaceOptions {
|
|
|
129
137
|
readonly layers?: readonly Layer[] | undefined;
|
|
130
138
|
readonly resources?: ResourceOverrideMap | undefined;
|
|
131
139
|
readonly resolvePermit?: ResolveMcpPermit | undefined;
|
|
140
|
+
/**
|
|
141
|
+
* Where callers reach this surface from.
|
|
142
|
+
*
|
|
143
|
+
* `host` (the default) is the in-process posture: the launching process is
|
|
144
|
+
* the caller, so a `createContext` permit and a host-supplied `extra.permit`
|
|
145
|
+
* are accepted as the host's own policy. `network` is the posture the
|
|
146
|
+
* fetch-shaped entry sets: identity enters only through `resolvePermit`,
|
|
147
|
+
* a `createContext` permit is discarded at runtime with a diagnostic,
|
|
148
|
+
* `extra.permit` is ignored, a presented bearer with no resolver is an
|
|
149
|
+
* `AuthError`, and protected trails without a resolver are refused at
|
|
150
|
+
* build time.
|
|
151
|
+
*/
|
|
152
|
+
readonly credentialPosture?: McpCredentialPosture | undefined;
|
|
132
153
|
}
|
|
133
154
|
|
|
155
|
+
/** See {@link DeriveMcpToolsOptions.credentialPosture}. */
|
|
156
|
+
export type McpCredentialPosture = 'host' | 'network';
|
|
157
|
+
|
|
134
158
|
export type McpSurfaceTrailheadTrailSelector = string | readonly string[];
|
|
135
159
|
|
|
136
160
|
/** Surface-side grouped entry over existing trails. */
|
|
@@ -151,10 +175,11 @@ export type McpSurfaceTrailheadMap = Readonly<
|
|
|
151
175
|
Record<string, McpSurfaceTrailheadDefinition>
|
|
152
176
|
>;
|
|
153
177
|
|
|
178
|
+
/** Untrusted request credential candidates; the configured resolver owns verification. */
|
|
154
179
|
export interface ResolveMcpPermitInput {
|
|
180
|
+
readonly _meta?: Readonly<Record<string, unknown>> | undefined;
|
|
155
181
|
readonly authorization?: string | undefined;
|
|
156
182
|
readonly bearerToken?: string | undefined;
|
|
157
|
-
readonly sessionId?: string | undefined;
|
|
158
183
|
}
|
|
159
184
|
|
|
160
185
|
export type ResolveMcpPermit = (
|
|
@@ -182,6 +207,8 @@ export interface McpToolDefinition {
|
|
|
182
207
|
}
|
|
183
208
|
|
|
184
209
|
export interface McpExtra {
|
|
210
|
+
/** Application metadata from this request, never proof of identity by itself. */
|
|
211
|
+
readonly _meta?: Readonly<Record<string, unknown>> | undefined;
|
|
185
212
|
readonly authorization?: string | undefined;
|
|
186
213
|
readonly progressToken?: string | number | undefined;
|
|
187
214
|
readonly sendProgress?:
|
|
@@ -189,7 +216,6 @@ export interface McpExtra {
|
|
|
189
216
|
| undefined;
|
|
190
217
|
readonly abortSignal?: AbortSignal | undefined;
|
|
191
218
|
readonly permit?: BasePermit | undefined;
|
|
192
|
-
readonly sessionId?: string | undefined;
|
|
193
219
|
}
|
|
194
220
|
|
|
195
221
|
export interface McpToolResult {
|
|
@@ -203,13 +229,8 @@ export type McpToolErrorMeta = Omit<SurfaceErrorRendering, 'surface'> & {
|
|
|
203
229
|
readonly surface: 'mcp';
|
|
204
230
|
};
|
|
205
231
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
readonly mimeType?: string | undefined;
|
|
209
|
-
readonly text?: string | undefined;
|
|
210
|
-
readonly type: 'text' | 'image' | 'resource';
|
|
211
|
-
readonly uri?: string | undefined;
|
|
212
|
-
}
|
|
232
|
+
/** MCP content emitted from trail results, validated by the SDK wire boundary. */
|
|
233
|
+
export type McpContent = TextContent | ImageContent | EmbeddedResource;
|
|
213
234
|
|
|
214
235
|
// ---------------------------------------------------------------------------
|
|
215
236
|
// Internal helpers (defined before use)
|
|
@@ -274,20 +295,20 @@ const blobToContent = async (
|
|
|
274
295
|
blob: BlobRef,
|
|
275
296
|
resolveData: BlobDataResolver = resolveBlobData
|
|
276
297
|
): Promise<McpContent> => {
|
|
298
|
+
const bytes = await resolveData(blob);
|
|
299
|
+
const data = uint8ArrayToBase64(bytes);
|
|
277
300
|
if (!blob.mimeType.startsWith('image/')) {
|
|
278
301
|
return {
|
|
279
|
-
|
|
302
|
+
resource: {
|
|
303
|
+
blob: data,
|
|
304
|
+
mimeType: blob.mimeType,
|
|
305
|
+
uri: `blob://${blob.name}`,
|
|
306
|
+
},
|
|
280
307
|
type: 'resource',
|
|
281
|
-
uri: `blob://${blob.name}`,
|
|
282
308
|
};
|
|
283
309
|
}
|
|
284
310
|
|
|
285
|
-
|
|
286
|
-
return {
|
|
287
|
-
data: uint8ArrayToBase64(bytes),
|
|
288
|
-
mimeType: blob.mimeType,
|
|
289
|
-
type: 'image',
|
|
290
|
-
};
|
|
311
|
+
return { data, mimeType: blob.mimeType, type: 'image' };
|
|
291
312
|
};
|
|
292
313
|
|
|
293
314
|
type BlobContentResolver = (blob: BlobRef) => Promise<McpContent>;
|
|
@@ -827,52 +848,6 @@ const withMcpSurface = (
|
|
|
827
848
|
progressCb === undefined ? {} : { progress: progressCb }
|
|
828
849
|
);
|
|
829
850
|
|
|
830
|
-
const parseBearerAuthorization = (
|
|
831
|
-
authorization: string | undefined
|
|
832
|
-
): Result<string | undefined, Error> => {
|
|
833
|
-
if (authorization === undefined || authorization.length === 0) {
|
|
834
|
-
return Result.ok();
|
|
835
|
-
}
|
|
836
|
-
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
|
837
|
-
const token = match?.[1]?.trim();
|
|
838
|
-
if (token === undefined || token.length === 0) {
|
|
839
|
-
return Result.err(
|
|
840
|
-
new AuthError('Malformed MCP authorization; expected Bearer token', {
|
|
841
|
-
context: { code: 'invalid_authorization_header' },
|
|
842
|
-
})
|
|
843
|
-
);
|
|
844
|
-
}
|
|
845
|
-
return Result.ok(token);
|
|
846
|
-
};
|
|
847
|
-
|
|
848
|
-
const resolveMcpPermit = async (
|
|
849
|
-
options: DeriveMcpToolsOptions,
|
|
850
|
-
extra: McpExtra
|
|
851
|
-
): Promise<Result<BasePermit | undefined, Error>> => {
|
|
852
|
-
if (extra.permit !== undefined) {
|
|
853
|
-
return Result.ok(extra.permit);
|
|
854
|
-
}
|
|
855
|
-
const token = parseBearerAuthorization(extra.authorization);
|
|
856
|
-
if (token.isErr()) {
|
|
857
|
-
return token;
|
|
858
|
-
}
|
|
859
|
-
if (token.value === undefined) {
|
|
860
|
-
return Result.ok();
|
|
861
|
-
}
|
|
862
|
-
if (options.resolvePermit === undefined) {
|
|
863
|
-
return Result.ok();
|
|
864
|
-
}
|
|
865
|
-
const resolved = await options.resolvePermit({
|
|
866
|
-
authorization: extra.authorization,
|
|
867
|
-
bearerToken: token.value,
|
|
868
|
-
sessionId: extra.sessionId,
|
|
869
|
-
});
|
|
870
|
-
if (resolved.isErr()) {
|
|
871
|
-
return resolved;
|
|
872
|
-
}
|
|
873
|
-
return Result.ok(resolved.value ?? undefined);
|
|
874
|
-
};
|
|
875
|
-
|
|
876
851
|
const createHandler =
|
|
877
852
|
(
|
|
878
853
|
graph: Topo,
|
|
@@ -903,7 +878,7 @@ const createHandler =
|
|
|
903
878
|
const result = await executeTrail(t, trailInput, {
|
|
904
879
|
abortSignal: extra.abortSignal,
|
|
905
880
|
configValues: options.configValues,
|
|
906
|
-
createContext: options
|
|
881
|
+
createContext: surfaceContextFactory(options),
|
|
907
882
|
ctx: withMcpSurface(progressCb, layers),
|
|
908
883
|
...(Object.keys(layerInputs).length === 0 ? {} : { layerInputs }),
|
|
909
884
|
...(permit === undefined ? {} : { permit }),
|
|
@@ -946,7 +921,7 @@ const buildDescription = (
|
|
|
946
921
|
): string | undefined => trail.description;
|
|
947
922
|
|
|
948
923
|
// MCP requires `outputSchema` to have literal `type: "object"` at the root
|
|
949
|
-
// (see `@modelcontextprotocol/
|
|
924
|
+
// (see `@modelcontextprotocol/server` Tool schema — `outputSchema: z.object({
|
|
950
925
|
// type: z.literal('object'), ... })`). Object-shaped unions like
|
|
951
926
|
// `z.discriminatedUnion(...)` emit as `{ anyOf: [...] }` from
|
|
952
927
|
// `zodToJsonSchema` with no top-level `type`, so we publish them under the
|
|
@@ -1269,10 +1244,53 @@ const eligibleTrails = (
|
|
|
1269
1244
|
intent: options.intent,
|
|
1270
1245
|
});
|
|
1271
1246
|
|
|
1247
|
+
const requiresVerifiedPermit = (
|
|
1248
|
+
trailItem: Trail<unknown, unknown, unknown>
|
|
1249
|
+
): boolean => trailItem.permit !== undefined && trailItem.permit !== 'public';
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* A network surface with protected trails and no verifier would fail every
|
|
1253
|
+
* protected call at runtime; refuse at build time so the gap teaches.
|
|
1254
|
+
*/
|
|
1255
|
+
const validateNetworkVerifier = (
|
|
1256
|
+
graph: Topo,
|
|
1257
|
+
options: DeriveMcpToolsOptions
|
|
1258
|
+
): Result<void, Error> => {
|
|
1259
|
+
if (
|
|
1260
|
+
options.credentialPosture !== 'network' ||
|
|
1261
|
+
options.resolvePermit !== undefined
|
|
1262
|
+
) {
|
|
1263
|
+
return Result.ok();
|
|
1264
|
+
}
|
|
1265
|
+
const protectedIds = eligibleTrails(graph, options)
|
|
1266
|
+
.filter((trailItem) => requiresVerifiedPermit(trailItem))
|
|
1267
|
+
.map((trailItem) => trailItem.id);
|
|
1268
|
+
if (protectedIds.length === 0) {
|
|
1269
|
+
return Result.ok();
|
|
1270
|
+
}
|
|
1271
|
+
return Result.err(
|
|
1272
|
+
new ValidationError(
|
|
1273
|
+
`MCP network surface exposes protected trails without a permit resolver: ${protectedIds.join(', ')}. Configure resolvePermit with a verifier, or exclude those trails from this surface. A createContext permit is not an identity source on a network surface.`,
|
|
1274
|
+
{
|
|
1275
|
+
context: {
|
|
1276
|
+
code: 'network_surface_missing_verifier',
|
|
1277
|
+
trailIds: protectedIds,
|
|
1278
|
+
},
|
|
1279
|
+
}
|
|
1280
|
+
)
|
|
1281
|
+
);
|
|
1282
|
+
};
|
|
1283
|
+
|
|
1272
1284
|
const validateToolBuild = (
|
|
1273
1285
|
graph: Topo,
|
|
1274
1286
|
options: DeriveMcpToolsOptions
|
|
1275
|
-
): Result<void, Error> =>
|
|
1287
|
+
): Result<void, Error> => {
|
|
1288
|
+
const validated = validateSurfaceTopo(graph, options);
|
|
1289
|
+
if (validated.isErr()) {
|
|
1290
|
+
return validated;
|
|
1291
|
+
}
|
|
1292
|
+
return validateNetworkVerifier(graph, options);
|
|
1293
|
+
};
|
|
1276
1294
|
|
|
1277
1295
|
const collectTrailheadMembers = (
|
|
1278
1296
|
graph: Topo,
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ValidationError } from '@ontrails/core';
|
|
2
|
+
|
|
3
|
+
/** Network/browser boundary configuration, independent of permit policy. */
|
|
4
|
+
export interface McpFetchBoundaryOptions {
|
|
5
|
+
readonly allowedHosts?: readonly string[] | undefined;
|
|
6
|
+
readonly allowedOrigins?: readonly string[] | undefined;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const invalidAuthority = /[\s/\\?#@,%*]/;
|
|
10
|
+
|
|
11
|
+
const parseAuthority = (
|
|
12
|
+
authority: string,
|
|
13
|
+
protocol: string
|
|
14
|
+
): URL | undefined => {
|
|
15
|
+
if (
|
|
16
|
+
authority.length === 0 ||
|
|
17
|
+
invalidAuthority.test(authority) ||
|
|
18
|
+
authority.endsWith(':')
|
|
19
|
+
) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
return new URL(`${protocol}//${authority}`);
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const parseOrigin = (value: string): URL | undefined => {
|
|
30
|
+
const match = /^https?:\/\/([^/?#]+)$/i.exec(value);
|
|
31
|
+
if (match?.[1] === undefined) {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
return parseAuthority(
|
|
35
|
+
match[1],
|
|
36
|
+
value.slice(0, value.indexOf(':') + 1).toLowerCase()
|
|
37
|
+
);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const effectivePort = (url: URL): string =>
|
|
41
|
+
url.port || (url.protocol === 'https:' ? '443' : '80');
|
|
42
|
+
|
|
43
|
+
/** Validate configuration once and guard each request before SDK dispatch. */
|
|
44
|
+
export const createMcpFetchBoundary = (
|
|
45
|
+
options: McpFetchBoundaryOptions
|
|
46
|
+
): ((request: Request) => Response | undefined) => {
|
|
47
|
+
const hosts = new Set(
|
|
48
|
+
(options.allowedHosts ?? ['localhost', '127.0.0.1', '[::1]']).map(
|
|
49
|
+
(value) => {
|
|
50
|
+
const url = parseAuthority(value, 'http:');
|
|
51
|
+
const hasPort = value.startsWith('[')
|
|
52
|
+
? !value.endsWith(']')
|
|
53
|
+
: value.includes(':');
|
|
54
|
+
if (
|
|
55
|
+
url === undefined ||
|
|
56
|
+
hasPort ||
|
|
57
|
+
url.hostname === '0.0.0.0' ||
|
|
58
|
+
url.hostname === '[::]'
|
|
59
|
+
) {
|
|
60
|
+
throw new ValidationError(`Invalid MCP allowed hostname: ${value}`);
|
|
61
|
+
}
|
|
62
|
+
return url.hostname;
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
);
|
|
66
|
+
const origins = new Set(
|
|
67
|
+
(options.allowedOrigins ?? []).map((value) => {
|
|
68
|
+
const url = parseOrigin(value);
|
|
69
|
+
if (url === undefined) {
|
|
70
|
+
throw new ValidationError(`Invalid MCP allowed origin: ${value}`);
|
|
71
|
+
}
|
|
72
|
+
return url.origin;
|
|
73
|
+
})
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
return (request) => {
|
|
77
|
+
const url = new URL(request.url);
|
|
78
|
+
if (
|
|
79
|
+
!['http:', 'https:'].includes(url.protocol) ||
|
|
80
|
+
!hosts.has(url.hostname)
|
|
81
|
+
) {
|
|
82
|
+
return new Response('Forbidden', { status: 403 });
|
|
83
|
+
}
|
|
84
|
+
const host = request.headers.get('host');
|
|
85
|
+
if (host !== null) {
|
|
86
|
+
const authority = parseAuthority(host, url.protocol);
|
|
87
|
+
if (
|
|
88
|
+
authority === undefined ||
|
|
89
|
+
authority.hostname !== url.hostname ||
|
|
90
|
+
effectivePort(authority) !== effectivePort(url)
|
|
91
|
+
) {
|
|
92
|
+
return new Response('Forbidden', { status: 403 });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const origin = request.headers.get('origin');
|
|
96
|
+
const parsed = origin === null ? undefined : parseOrigin(origin);
|
|
97
|
+
return origin !== null &&
|
|
98
|
+
(parsed === undefined || !origins.has(parsed.origin))
|
|
99
|
+
? new Response('Forbidden', { status: 403 })
|
|
100
|
+
: undefined;
|
|
101
|
+
};
|
|
102
|
+
};
|
package/src/fetch.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { createMcpHandler } from '@modelcontextprotocol/server';
|
|
2
|
+
import type { Server } from '@modelcontextprotocol/server';
|
|
3
|
+
import type { Topo } from '@ontrails/core';
|
|
4
|
+
|
|
5
|
+
import { createMcpFetchBoundary } from './fetch-boundary.js';
|
|
6
|
+
import type { McpFetchBoundaryOptions } from './fetch-boundary.js';
|
|
7
|
+
import { createServerFactory } from './server.js';
|
|
8
|
+
import type { CreateServerOptions } from './server.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Options for the portable MCP HTTP entry, separate from runtime hosting.
|
|
12
|
+
*
|
|
13
|
+
* The entry always builds with the `network` credential posture: identity
|
|
14
|
+
* enters only through `resolvePermit`, a `createContext` permit is
|
|
15
|
+
* discarded at runtime, and protected trails without a resolver are refused
|
|
16
|
+
* at build time. The posture is not configurable here.
|
|
17
|
+
*/
|
|
18
|
+
export interface CreateMcpFetchHandlerOptions
|
|
19
|
+
extends
|
|
20
|
+
Omit<CreateServerOptions, 'credentialPosture'>,
|
|
21
|
+
McpFetchBoundaryOptions {}
|
|
22
|
+
|
|
23
|
+
/** Portable request handler with teardown of active server instances and streams. */
|
|
24
|
+
export interface McpFetchHandler {
|
|
25
|
+
readonly fetch: (request: Request) => Promise<Response>;
|
|
26
|
+
readonly close: () => Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Serve modern MCP and legacy stateless HTTP through one fresh server factory.
|
|
31
|
+
*
|
|
32
|
+
* Host and Origin checks run before SDK dispatch. Raw request authorization
|
|
33
|
+
* reaches the existing permit resolver; this entry never fabricates SDK authInfo.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* import { createFetchHandler } from '@ontrails/mcp/fetch';
|
|
38
|
+
* const mcp = createFetchHandler(graph);
|
|
39
|
+
* const server = Bun.serve({ fetch: mcp.fetch });
|
|
40
|
+
* // On shutdown: await mcp.close(); server.stop();
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export const createFetchHandler = (
|
|
44
|
+
graph: Topo,
|
|
45
|
+
options: CreateMcpFetchHandlerOptions = {}
|
|
46
|
+
): McpFetchHandler => {
|
|
47
|
+
const guard = createMcpFetchBoundary(options);
|
|
48
|
+
const factory = createServerFactory(graph, {
|
|
49
|
+
...options,
|
|
50
|
+
credentialPosture: 'network',
|
|
51
|
+
});
|
|
52
|
+
const instances = new Set<Server>();
|
|
53
|
+
let closed = false;
|
|
54
|
+
const handler = createMcpHandler(
|
|
55
|
+
(context) => {
|
|
56
|
+
if (closed) {
|
|
57
|
+
throw new Error('This MCP handler has been closed');
|
|
58
|
+
}
|
|
59
|
+
const authorization = context.requestInfo?.headers.get('authorization');
|
|
60
|
+
const server = factory(
|
|
61
|
+
authorization === null || authorization === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: { authorization }
|
|
64
|
+
);
|
|
65
|
+
instances.add(server);
|
|
66
|
+
const previousOnClose = server.onclose;
|
|
67
|
+
// oxlint-disable-next-line unicorn/prefer-add-event-listener -- SDK Server exposes onclose rather than EventTarget; preserve its callback.
|
|
68
|
+
server.onclose = () => {
|
|
69
|
+
instances.delete(server);
|
|
70
|
+
previousOnClose?.();
|
|
71
|
+
};
|
|
72
|
+
return server;
|
|
73
|
+
},
|
|
74
|
+
{ legacy: 'stateless' }
|
|
75
|
+
);
|
|
76
|
+
return {
|
|
77
|
+
close: async () => {
|
|
78
|
+
closed = true;
|
|
79
|
+
await handler.close();
|
|
80
|
+
// SDK teardown tracks modern exchanges only; legacy instances need the same shutdown.
|
|
81
|
+
await Promise.all([...instances].map((server) => server.close()));
|
|
82
|
+
instances.clear();
|
|
83
|
+
},
|
|
84
|
+
fetch: async (request) => guard(request) ?? handler.fetch(request),
|
|
85
|
+
};
|
|
86
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ export {
|
|
|
6
6
|
MCP_TOOL_TRAILHEAD_META_KEY,
|
|
7
7
|
deriveMcpTools,
|
|
8
8
|
type DeriveMcpToolsOptions,
|
|
9
|
+
type McpCredentialPosture,
|
|
9
10
|
type McpSurfaceTrailheadDefinition,
|
|
10
11
|
type McpSurfaceTrailheadMap,
|
|
11
12
|
type McpSurfaceTrailheadTrailSelector,
|
|
@@ -31,6 +32,23 @@ export {
|
|
|
31
32
|
type McpResourcesConfig,
|
|
32
33
|
} from './resources.js';
|
|
33
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Policy over verified callers and canonical MCP resource descriptors.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* const options: CreateServerOptions = {
|
|
41
|
+
* authorizeResourceRead: ({ permit }) => permit
|
|
42
|
+
* ? Result.ok()
|
|
43
|
+
* : Result.err(new PermissionError('Sign in to read resources')),
|
|
44
|
+
* };
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export type {
|
|
48
|
+
AuthorizeMcpResourceRead,
|
|
49
|
+
AuthorizeMcpResourceReadInput,
|
|
50
|
+
} from './resource-access.js';
|
|
51
|
+
|
|
34
52
|
// Tool naming
|
|
35
53
|
export { deriveToolName } from './tool-name.js';
|
|
36
54
|
|
|
@@ -40,13 +58,11 @@ export { deriveAnnotations, type McpAnnotations } from './annotations.js';
|
|
|
40
58
|
// Progress
|
|
41
59
|
export { createMcpProgressCallback } from './progress.js';
|
|
42
60
|
|
|
61
|
+
// Server
|
|
62
|
+
export { createServer, type CreateServerOptions } from './server.js';
|
|
63
|
+
|
|
43
64
|
// Surface
|
|
44
|
-
export {
|
|
45
|
-
createServer,
|
|
46
|
-
surface,
|
|
47
|
-
type CreateServerOptions,
|
|
48
|
-
type SurfaceMcpResult,
|
|
49
|
-
} from './surface.js';
|
|
65
|
+
export { surface, type SurfaceMcpResult } from './surface.js';
|
|
50
66
|
|
|
51
67
|
// Transport
|
|
52
68
|
export { connectStdio } from './stdio.js';
|