@ontrails/mcp 0.2.4 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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';
@@ -0,0 +1,67 @@
1
+ import { zodToJsonSchema } from '@ontrails/core';
2
+
3
+ import type { McpToolDefinition, McpToolResult } from './build.js';
4
+
5
+ /** Canonical output facts and the compatibility rendering, derived together. */
6
+ export interface McpOutputRendering {
7
+ readonly schema: Record<string, unknown>;
8
+ readonly legacySchema: Record<string, unknown>;
9
+ readonly legacyWrapAsData: boolean;
10
+ }
11
+
12
+ /** Internal runtime values may be any structured JSON value on the modern era. */
13
+ export interface McpRuntimeResult extends Omit<
14
+ McpToolResult,
15
+ 'structuredContent'
16
+ > {
17
+ readonly structuredContent?: unknown;
18
+ }
19
+
20
+ export interface McpRuntimeTool extends Omit<McpToolDefinition, 'handler'> {
21
+ readonly handler: (
22
+ args: Record<string, unknown>,
23
+ extra: Parameters<McpToolDefinition['handler']>[1]
24
+ ) => Promise<McpRuntimeResult>;
25
+ }
26
+
27
+ /** Package-private views share one authored execution and schema derivation. */
28
+ export interface McpToolRecord {
29
+ readonly legacy: McpToolDefinition;
30
+ readonly modern: McpRuntimeTool;
31
+ }
32
+
33
+ export const deriveMcpOutputRendering = (
34
+ output: Parameters<typeof zodToJsonSchema>[0]
35
+ ): McpOutputRendering => {
36
+ const schema = zodToJsonSchema(output);
37
+ const legacyWrapAsData = schema['type'] !== 'object';
38
+ return {
39
+ legacySchema: legacyWrapAsData
40
+ ? { properties: { data: schema }, required: ['data'], type: 'object' }
41
+ : schema,
42
+ legacyWrapAsData,
43
+ schema,
44
+ };
45
+ };
46
+
47
+ export const renderLegacyMcpResult = (
48
+ result: McpRuntimeResult,
49
+ rendering?: McpOutputRendering
50
+ ): McpToolResult => {
51
+ if (result.isError === true) {
52
+ const { structuredContent: _omitted, ...error } = result;
53
+ return error;
54
+ }
55
+ const value = result.structuredContent;
56
+ let structuredContent: Record<string, unknown> | undefined;
57
+ if (rendering?.legacyWrapAsData === true) {
58
+ structuredContent = { data: value };
59
+ } else if (
60
+ value !== null &&
61
+ typeof value === 'object' &&
62
+ !Array.isArray(value)
63
+ ) {
64
+ structuredContent = value as Record<string, unknown>;
65
+ }
66
+ return { ...result, structuredContent };
67
+ };
@@ -0,0 +1,102 @@
1
+ import { AuthError, Result } from '@ontrails/core';
2
+ import type { BasePermit, TrailContextInit } from '@ontrails/core';
3
+
4
+ import type { DeriveMcpToolsOptions, McpExtra } from './build.js';
5
+
6
+ const SEEDED_PERMIT_DIAGNOSTIC =
7
+ '[ontrails:mcp] A createContext permit was discarded on a network MCP surface. Identity enters a network surface only through resolvePermit; move the credential into a verifier (see the @ontrails/mcp changelog for TRL-1560).';
8
+
9
+ let seededPermitDiagnosed = false;
10
+
11
+ /**
12
+ * The context factory a surface hands to the pipeline.
13
+ *
14
+ * On the network posture a seeded permit is discarded at runtime (once with a
15
+ * diagnostic) so an anonymous caller can never inherit host identity; the
16
+ * rest of the seed (logger, extensions, resources) still applies.
17
+ */
18
+ export const surfaceContextFactory = (
19
+ options: Pick<DeriveMcpToolsOptions, 'createContext' | 'credentialPosture'>
20
+ ): (() => TrailContextInit | Promise<TrailContextInit>) | undefined => {
21
+ const factory = options.createContext;
22
+ if (factory === undefined || options.credentialPosture !== 'network') {
23
+ return factory;
24
+ }
25
+ return async () => {
26
+ const { permit, ...seed } = await factory();
27
+ if (permit !== undefined && !seededPermitDiagnosed) {
28
+ seededPermitDiagnosed = true;
29
+ // The seed's own logger is the app's logging surface; a seed without one
30
+ // still loses the permit, silently.
31
+ seed.logger?.warn(SEEDED_PERMIT_DIAGNOSTIC, {
32
+ code: 'seeded_permit_discarded',
33
+ permitId: permit.id,
34
+ });
35
+ }
36
+ return seed;
37
+ };
38
+ };
39
+
40
+ /** Test seam: forget that the seeded-permit diagnostic was emitted. */
41
+ export const resetSeededPermitDiagnostic = (): void => {
42
+ seededPermitDiagnosed = false;
43
+ };
44
+
45
+ const parseBearerAuthorization = (
46
+ authorization: string | undefined
47
+ ): Result<string | undefined, Error> => {
48
+ if (authorization === undefined || authorization.length === 0) {
49
+ return Result.ok();
50
+ }
51
+ const match = authorization.match(/^Bearer\s+(.+)$/i);
52
+ const token = match?.[1]?.trim();
53
+ if (token === undefined || token.length === 0) {
54
+ return Result.err(
55
+ new AuthError('Malformed MCP authorization; expected Bearer token', {
56
+ context: { code: 'invalid_authorization_header' },
57
+ })
58
+ );
59
+ }
60
+ return Result.ok(token);
61
+ };
62
+
63
+ /**
64
+ * Resolve one request's untrusted candidates, preserving trusted host permits.
65
+ *
66
+ * Shared seam for MCP invocation and resource adapters. The configured resolver
67
+ * owns accepted credential syntax; malformed Bearer is not absence by policy.
68
+ * Callers own subsequent trusted host-context fallback, never after an error.
69
+ */
70
+ export const resolveMcpPermit = async (
71
+ options: Pick<DeriveMcpToolsOptions, 'resolvePermit' | 'credentialPosture'>,
72
+ extra: Pick<McpExtra, '_meta' | 'authorization' | 'permit'>
73
+ ): Promise<Result<BasePermit | undefined, Error>> => {
74
+ const network = options.credentialPosture === 'network';
75
+ if (extra.permit !== undefined && !network) {
76
+ return Result.ok(extra.permit);
77
+ }
78
+ const token = parseBearerAuthorization(extra.authorization);
79
+ if (options.resolvePermit === undefined) {
80
+ if (token.isErr()) {
81
+ return token;
82
+ }
83
+ if (network && token.value !== undefined) {
84
+ return Result.err(
85
+ new AuthError(
86
+ 'A bearer credential was presented but this MCP surface has no permit resolver; configure resolvePermit with a verifier.',
87
+ { context: { code: 'no_permit_resolver' } }
88
+ )
89
+ );
90
+ }
91
+ return Result.ok();
92
+ }
93
+ const resolved = await options.resolvePermit({
94
+ _meta: extra._meta,
95
+ authorization: extra.authorization,
96
+ bearerToken: token.isOk() ? token.value : undefined,
97
+ });
98
+ if (resolved.isErr()) {
99
+ return resolved;
100
+ }
101
+ return Result.ok(resolved.value ?? undefined);
102
+ };
@@ -0,0 +1,71 @@
1
+ import { ProtocolError } from '@modelcontextprotocol/server';
2
+ import { Result, renderJsonRpcError } from '@ontrails/core';
3
+ import type { BasePermit } from '@ontrails/core';
4
+
5
+ import type { McpExtra } from './build.js';
6
+ import {
7
+ resolveMcpPermit,
8
+ surfaceContextFactory,
9
+ } from './permit-resolution.js';
10
+ import type { McpResourceDefinition } from './resources.js';
11
+ import type { CreateServerOptions } from './server.js';
12
+
13
+ /** Verified caller and canonical resource descriptor, without invocation scopes. */
14
+ export interface AuthorizeMcpResourceReadInput {
15
+ readonly permit: BasePermit | undefined;
16
+ readonly resource: McpResourceDefinition;
17
+ }
18
+
19
+ /**
20
+ * Authorize one resource URI for listing or reading.
21
+ *
22
+ * Return `Result.ok()` to allow it, or a `PermissionError` to deny it. Listing
23
+ * omits denied resources; other errors fail the request. Direct reads report
24
+ * the error through the shared JSON-RPC rendering. Omission means public reads.
25
+ */
26
+ export type AuthorizeMcpResourceRead = (
27
+ input: AuthorizeMcpResourceReadInput
28
+ ) => Result<void, Error> | Promise<Result<void, Error>>;
29
+
30
+ /**
31
+ * Preserve tool execution's request-permit precedence over trusted host context.
32
+ *
33
+ * Mirrors the context permit fallback in packages/core/src/execute.ts:294.
34
+ * Credential errors return before consulting the host factory.
35
+ */
36
+ export const resolveMcpResourcePermit = async (
37
+ options: Pick<
38
+ CreateServerOptions,
39
+ 'resolvePermit' | 'createContext' | 'credentialPosture'
40
+ >,
41
+ extra: Pick<McpExtra, '_meta' | 'authorization' | 'permit'>
42
+ ): Promise<Result<BasePermit | undefined, Error>> => {
43
+ const resolved = await resolveMcpPermit(options, extra);
44
+ if (resolved.isErr() || resolved.value !== undefined) {
45
+ return resolved;
46
+ }
47
+ // The network posture strips the seeded permit, so this fallback only
48
+ // carries host policy for in-process surfaces.
49
+ const context = await surfaceContextFactory(options)?.();
50
+ return Result.ok(context?.permit);
51
+ };
52
+
53
+ /** Render expected failures and unexpected app exceptions through one public boundary. */
54
+ export const runMcpResourceRequest = async <T>(
55
+ method: 'resources/read' | undefined,
56
+ operation: () => Promise<Result<T, Error>>
57
+ ): Promise<T> => {
58
+ let result: Result<T, Error>;
59
+ try {
60
+ result = await operation();
61
+ } catch (error) {
62
+ result = Result.err(
63
+ error instanceof Error ? error : new Error('MCP resource request failed')
64
+ );
65
+ }
66
+ if (result.isErr()) {
67
+ const error = renderJsonRpcError('mcp', result.error, method);
68
+ throw new ProtocolError(error.code, error.message, error.data);
69
+ }
70
+ return result.value;
71
+ };
package/src/resources.ts CHANGED
@@ -11,6 +11,9 @@ import {
11
11
  } from './build.js';
12
12
  import type { McpToolDefinition } from './build.js';
13
13
 
14
+ // Resource rendering consumes contract facts, never the invocation callback.
15
+ type McpResourceTool = Omit<McpToolDefinition, 'handler'>;
16
+
14
17
  /**
15
18
  * Resource URI used for the resolved MCP surface map.
16
19
  *
@@ -52,6 +55,8 @@ export interface McpResourceDefinition {
52
55
  readonly mimeType: string;
53
56
  readonly name: string;
54
57
  readonly description?: string | undefined;
58
+ /** Authored trail identity for trail-specific resources; absent for aggregates. */
59
+ readonly trailId?: string | undefined;
55
60
  }
56
61
 
57
62
  export interface McpResourceContent {
@@ -107,7 +112,7 @@ interface McpTrailResource {
107
112
  const asJson = (value: unknown): string =>
108
113
  `${JSON.stringify(value, null, 2)}\n`;
109
114
 
110
- const renderSurfaceMapTool = (tool: McpToolDefinition): McpSurfaceMapTool => ({
115
+ const renderSurfaceMapTool = (tool: McpResourceTool): McpSurfaceMapTool => ({
111
116
  annotations: tool.annotations,
112
117
  description: tool.description,
113
118
  inputSchema: tool.inputSchema,
@@ -126,15 +131,13 @@ const renderSurfaceMapTool = (tool: McpToolDefinition): McpSurfaceMapTool => ({
126
131
  : {}),
127
132
  });
128
133
 
129
- const buildSurfaceMap = (
130
- tools: readonly McpToolDefinition[]
131
- ): McpSurfaceMap => ({
134
+ const buildSurfaceMap = (tools: readonly McpResourceTool[]): McpSurfaceMap => ({
132
135
  surface: 'mcp',
133
136
  tools: tools.map(renderSurfaceMapTool),
134
137
  });
135
138
 
136
139
  const exposedTrailIds = (
137
- tools: readonly McpToolDefinition[]
140
+ tools: readonly McpResourceTool[]
138
141
  ): ReadonlySet<string> =>
139
142
  new Set(
140
143
  tools.flatMap((tool) => [
@@ -176,6 +179,7 @@ const buildExampleResource = (
176
179
  description: `Structured examples for trail "${trailItem.id}".`,
177
180
  mimeType: 'application/json',
178
181
  name: `Trail examples: ${trailItem.id}`,
182
+ trailId: trailItem.id,
179
183
  uri,
180
184
  },
181
185
  };
@@ -183,7 +187,7 @@ const buildExampleResource = (
183
187
 
184
188
  const buildExampleResources = (
185
189
  graph: Topo,
186
- tools: readonly McpToolDefinition[]
190
+ tools: readonly McpResourceTool[]
187
191
  ): readonly {
188
192
  readonly content: McpResourceContent;
189
193
  readonly listing: McpResourceDefinition;
@@ -204,7 +208,7 @@ const resourceId = (
204
208
 
205
209
  const buildTrailGraphResource = (
206
210
  trailItem: Trail<unknown, unknown, unknown>,
207
- tools: readonly McpToolDefinition[]
211
+ tools: readonly McpResourceTool[]
208
212
  ): {
209
213
  readonly content: McpResourceContent;
210
214
  readonly listing: McpResourceDefinition;
@@ -244,6 +248,7 @@ const buildTrailGraphResource = (
244
248
  description: `MCP-visible graph facts for trail "${trailItem.id}".`,
245
249
  mimeType: 'application/json',
246
250
  name: `Trail graph fact: ${trailItem.id}`,
251
+ trailId: trailItem.id,
247
252
  uri,
248
253
  },
249
254
  };
@@ -251,7 +256,7 @@ const buildTrailGraphResource = (
251
256
 
252
257
  const buildTrailGraphResources = (
253
258
  graph: Topo,
254
- tools: readonly McpToolDefinition[]
259
+ tools: readonly McpResourceTool[]
255
260
  ): readonly {
256
261
  readonly content: McpResourceContent;
257
262
  readonly listing: McpResourceDefinition;
@@ -281,7 +286,7 @@ const buildTrailGraphResources = (
281
286
  */
282
287
  export const buildMcpResources = (
283
288
  graph: Topo,
284
- tools: readonly McpToolDefinition[],
289
+ tools: readonly McpResourceTool[],
285
290
  config: McpResourcesConfig = {}
286
291
  ): BuiltMcpResources => {
287
292
  const listings: McpResourceDefinition[] = [];