@ontrails/mcp 0.2.4 → 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 +30 -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
|
@@ -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
|
@@ -52,6 +52,8 @@ export interface McpResourceDefinition {
|
|
|
52
52
|
readonly mimeType: string;
|
|
53
53
|
readonly name: string;
|
|
54
54
|
readonly description?: string | undefined;
|
|
55
|
+
/** Authored trail identity for trail-specific resources; absent for aggregates. */
|
|
56
|
+
readonly trailId?: string | undefined;
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
export interface McpResourceContent {
|
|
@@ -176,6 +178,7 @@ const buildExampleResource = (
|
|
|
176
178
|
description: `Structured examples for trail "${trailItem.id}".`,
|
|
177
179
|
mimeType: 'application/json',
|
|
178
180
|
name: `Trail examples: ${trailItem.id}`,
|
|
181
|
+
trailId: trailItem.id,
|
|
179
182
|
uri,
|
|
180
183
|
},
|
|
181
184
|
};
|
|
@@ -244,6 +247,7 @@ const buildTrailGraphResource = (
|
|
|
244
247
|
description: `MCP-visible graph facts for trail "${trailItem.id}".`,
|
|
245
248
|
mimeType: 'application/json',
|
|
246
249
|
name: `Trail graph fact: ${trailItem.id}`,
|
|
250
|
+
trailId: trailItem.id,
|
|
247
251
|
uri,
|
|
248
252
|
},
|
|
249
253
|
};
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Surface helpers for exposing a topo over MCP.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { Server } from '@modelcontextprotocol/server';
|
|
6
|
+
import type { ServerContext } from '@modelcontextprotocol/server';
|
|
7
|
+
import { NotFoundError, PermissionError, Result } from '@ontrails/core';
|
|
8
|
+
import type {
|
|
9
|
+
BaseSurfaceOptions,
|
|
10
|
+
Layer,
|
|
11
|
+
OverlayEnvelopeLike,
|
|
12
|
+
ResourceOverrideMap,
|
|
13
|
+
Topo,
|
|
14
|
+
TrailContextInit,
|
|
15
|
+
} from '@ontrails/core';
|
|
16
|
+
|
|
17
|
+
import type {
|
|
18
|
+
McpSurfaceTrailheadMap,
|
|
19
|
+
McpExtra,
|
|
20
|
+
McpToolDefinition,
|
|
21
|
+
ResolveMcpPermit,
|
|
22
|
+
McpCredentialPosture,
|
|
23
|
+
} from './build.js';
|
|
24
|
+
import { deriveMcpTools } from './build.js';
|
|
25
|
+
import {
|
|
26
|
+
resolveMcpResourcePermit,
|
|
27
|
+
runMcpResourceRequest,
|
|
28
|
+
} from './resource-access.js';
|
|
29
|
+
import type { AuthorizeMcpResourceRead } from './resource-access.js';
|
|
30
|
+
import { buildMcpResources } from './resources.js';
|
|
31
|
+
import type { BuiltMcpResources, McpResourcesConfig } from './resources.js';
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Options
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
export interface CreateServerOptions extends BaseSurfaceOptions {
|
|
38
|
+
/** Optional read policy; permission denials also omit URIs from resource lists. */
|
|
39
|
+
readonly authorizeResourceRead?: AuthorizeMcpResourceRead | undefined;
|
|
40
|
+
readonly createContext?:
|
|
41
|
+
| (() => TrailContextInit | Promise<TrailContextInit>)
|
|
42
|
+
| undefined;
|
|
43
|
+
readonly description?: string | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* App-authored overlay envelopes (the same collection compile embeds in
|
|
46
|
+
* `trails.lock`). The `surfaces` overlay's `mcp` bindings are the authored,
|
|
47
|
+
* lockable default: list bindings become grouped trailhead tools and scalar
|
|
48
|
+
* bindings become tool synonyms.
|
|
49
|
+
*/
|
|
50
|
+
readonly overlays?: readonly OverlayEnvelopeLike[] | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Call-site trailhead map. Override-in-context by design: when both this
|
|
53
|
+
* map and overlay `mcp` list bindings are present, the call-site map wins
|
|
54
|
+
* at runtime.
|
|
55
|
+
*/
|
|
56
|
+
readonly trailheads?: McpSurfaceTrailheadMap | undefined;
|
|
57
|
+
readonly layers?: readonly Layer[] | undefined;
|
|
58
|
+
readonly mcpResources?: McpResourcesConfig | false | undefined;
|
|
59
|
+
readonly name?: string | undefined;
|
|
60
|
+
readonly resources?: ResourceOverrideMap | undefined;
|
|
61
|
+
readonly resolvePermit?: ResolveMcpPermit | undefined;
|
|
62
|
+
/** See `DeriveMcpToolsOptions.credentialPosture`; the fetch entry forces `network`. */
|
|
63
|
+
readonly credentialPosture?: McpCredentialPosture | undefined;
|
|
64
|
+
readonly version?: string | undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
// Internal: create MCP server with tool handlers
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
const requestCredentials = (
|
|
72
|
+
context: ServerContext,
|
|
73
|
+
credentials?: Pick<McpExtra, 'authorization'>
|
|
74
|
+
): Pick<McpExtra, '_meta' | 'authorization'> => {
|
|
75
|
+
const token = context.http?.authInfo?.token;
|
|
76
|
+
const authorization =
|
|
77
|
+
credentials?.authorization ??
|
|
78
|
+
(token === undefined ? undefined : `Bearer ${token}`);
|
|
79
|
+
return {
|
|
80
|
+
_meta: context.mcpReq._meta,
|
|
81
|
+
...(authorization === undefined ? {} : { authorization }),
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Create an MCP Server instance and register all tools.
|
|
87
|
+
*
|
|
88
|
+
* When provided, `info.description` is forwarded to the MCP SDK as the
|
|
89
|
+
* server's `instructions` field — the SDK's documented channel for
|
|
90
|
+
* "optional instructions describing how to use the server and its features."
|
|
91
|
+
*/
|
|
92
|
+
const createMcpServer = (
|
|
93
|
+
tools: McpToolDefinition[],
|
|
94
|
+
info: {
|
|
95
|
+
readonly name: string;
|
|
96
|
+
readonly version: string;
|
|
97
|
+
readonly description?: string | undefined;
|
|
98
|
+
},
|
|
99
|
+
mcpResources: BuiltMcpResources | undefined,
|
|
100
|
+
options: CreateServerOptions,
|
|
101
|
+
credentials?: Pick<McpExtra, 'authorization'>
|
|
102
|
+
): Server => {
|
|
103
|
+
const server = new Server(
|
|
104
|
+
{ name: info.name, version: info.version },
|
|
105
|
+
{
|
|
106
|
+
capabilities: {
|
|
107
|
+
...(mcpResources === undefined ? {} : { resources: {} }),
|
|
108
|
+
tools: {},
|
|
109
|
+
},
|
|
110
|
+
...(info.description === undefined
|
|
111
|
+
? {}
|
|
112
|
+
: { instructions: info.description }),
|
|
113
|
+
}
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
// Build a lookup map for tool dispatch
|
|
117
|
+
const toolMap = new Map<string, McpToolDefinition>();
|
|
118
|
+
for (const tool of tools) {
|
|
119
|
+
toolMap.set(tool.name, tool);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Register tools/list handler
|
|
123
|
+
// oxlint-disable-next-line require-await -- MCP SDK requires async handler
|
|
124
|
+
server.setRequestHandler('tools/list', async () => ({
|
|
125
|
+
tools: tools.map((t) => ({
|
|
126
|
+
_meta: t._meta,
|
|
127
|
+
annotations: t.annotations,
|
|
128
|
+
description: t.description,
|
|
129
|
+
inputSchema: { ...t.inputSchema, type: 'object' as const },
|
|
130
|
+
name: t.name,
|
|
131
|
+
outputSchema:
|
|
132
|
+
t.outputSchema === undefined
|
|
133
|
+
? undefined
|
|
134
|
+
: { ...t.outputSchema, type: 'object' as const },
|
|
135
|
+
})),
|
|
136
|
+
}));
|
|
137
|
+
|
|
138
|
+
// Register tools/call handler
|
|
139
|
+
server.setRequestHandler('tools/call', async (request, requestExtra) => {
|
|
140
|
+
const tool = toolMap.get(request.params.name);
|
|
141
|
+
if (tool === undefined) {
|
|
142
|
+
return {
|
|
143
|
+
content: [
|
|
144
|
+
{
|
|
145
|
+
text: `Unknown tool: ${request.params.name}`,
|
|
146
|
+
type: 'text' as const,
|
|
147
|
+
},
|
|
148
|
+
],
|
|
149
|
+
isError: true,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const args = (request.params.arguments ?? {}) as Record<string, unknown>;
|
|
154
|
+
const progressToken = requestExtra.mcpReq._meta?.progressToken;
|
|
155
|
+
|
|
156
|
+
const sendProgress =
|
|
157
|
+
progressToken === undefined
|
|
158
|
+
? undefined
|
|
159
|
+
: async (current: number, total: number) => {
|
|
160
|
+
await requestExtra.mcpReq.notify({
|
|
161
|
+
method: 'notifications/progress',
|
|
162
|
+
params: { progress: current, progressToken, total },
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const extra = {
|
|
167
|
+
...requestCredentials(requestExtra, credentials),
|
|
168
|
+
abortSignal: requestExtra.mcpReq.signal,
|
|
169
|
+
progressToken,
|
|
170
|
+
sendProgress,
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const result = await tool.handler(args, extra);
|
|
174
|
+
// Copy the readonly content list into the SDK result shape.
|
|
175
|
+
return server.projectCallToolResult(
|
|
176
|
+
{ ...result, content: [...result.content] },
|
|
177
|
+
tool.outputSchema
|
|
178
|
+
);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
if (mcpResources !== undefined) {
|
|
182
|
+
server.setRequestHandler('resources/list', (_request, requestExtra) =>
|
|
183
|
+
runMcpResourceRequest(undefined, async () => {
|
|
184
|
+
const permit = await resolveMcpResourcePermit(
|
|
185
|
+
options,
|
|
186
|
+
requestCredentials(requestExtra, credentials)
|
|
187
|
+
);
|
|
188
|
+
if (permit.isErr()) {
|
|
189
|
+
return permit;
|
|
190
|
+
}
|
|
191
|
+
const resources = [];
|
|
192
|
+
for (const resource of mcpResources.list) {
|
|
193
|
+
if (options.authorizeResourceRead !== undefined) {
|
|
194
|
+
const allowed = await options.authorizeResourceRead({
|
|
195
|
+
permit: permit.value,
|
|
196
|
+
resource,
|
|
197
|
+
});
|
|
198
|
+
if (allowed.isErr()) {
|
|
199
|
+
if (allowed.error instanceof PermissionError) {
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
return allowed;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
resources.push({
|
|
206
|
+
description: resource.description,
|
|
207
|
+
mimeType: resource.mimeType,
|
|
208
|
+
name: resource.name,
|
|
209
|
+
uri: resource.uri,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return Result.ok({ resources });
|
|
213
|
+
})
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
server.setRequestHandler('resources/read', (request, requestExtra) =>
|
|
217
|
+
runMcpResourceRequest('resources/read', async () => {
|
|
218
|
+
const permit = await resolveMcpResourcePermit(
|
|
219
|
+
options,
|
|
220
|
+
requestCredentials(requestExtra, credentials)
|
|
221
|
+
);
|
|
222
|
+
if (permit.isErr()) {
|
|
223
|
+
return permit;
|
|
224
|
+
}
|
|
225
|
+
const resource = mcpResources.list.find(
|
|
226
|
+
(entry) => entry.uri === request.params.uri
|
|
227
|
+
);
|
|
228
|
+
if (resource === undefined) {
|
|
229
|
+
return Result.err(
|
|
230
|
+
new NotFoundError(`Resource ${request.params.uri} not found`)
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (options.authorizeResourceRead !== undefined) {
|
|
234
|
+
const allowed = await options.authorizeResourceRead({
|
|
235
|
+
permit: permit.value,
|
|
236
|
+
resource,
|
|
237
|
+
});
|
|
238
|
+
if (allowed.isErr()) {
|
|
239
|
+
return allowed;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const content = mcpResources.read(resource.uri);
|
|
243
|
+
if (content === undefined) {
|
|
244
|
+
return Result.err(
|
|
245
|
+
new NotFoundError(`Resource ${resource.uri} not found`)
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
return Result.ok({ contents: [content] });
|
|
249
|
+
})
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return server;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// createServer
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
/** Build fresh portable server instances from one derived surface. @internal */
|
|
261
|
+
export const createServerFactory = (
|
|
262
|
+
graph: Topo,
|
|
263
|
+
options: CreateServerOptions = {}
|
|
264
|
+
): ((credentials?: Pick<McpExtra, 'authorization'>) => Server) => {
|
|
265
|
+
const toolsResult = deriveMcpTools(graph, {
|
|
266
|
+
configValues: options.configValues,
|
|
267
|
+
createContext: options.createContext,
|
|
268
|
+
credentialPosture: options.credentialPosture,
|
|
269
|
+
exclude: options.exclude,
|
|
270
|
+
include: options.include,
|
|
271
|
+
intent: options.intent,
|
|
272
|
+
layers: options.layers,
|
|
273
|
+
overlays: options.overlays,
|
|
274
|
+
resolvePermit: options.resolvePermit,
|
|
275
|
+
resources: options.resources,
|
|
276
|
+
trailheads: options.trailheads,
|
|
277
|
+
validate: options.validate,
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
if (toolsResult.isErr()) {
|
|
281
|
+
throw toolsResult.error;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const mcpResources =
|
|
285
|
+
options.mcpResources === false
|
|
286
|
+
? undefined
|
|
287
|
+
: buildMcpResources(graph, toolsResult.value, options.mcpResources);
|
|
288
|
+
|
|
289
|
+
return (credentials) =>
|
|
290
|
+
createMcpServer(
|
|
291
|
+
toolsResult.value,
|
|
292
|
+
{
|
|
293
|
+
description: options.description ?? graph.description,
|
|
294
|
+
name: options.name ?? graph.name,
|
|
295
|
+
version: options.version ?? graph.version ?? '0.1.0',
|
|
296
|
+
},
|
|
297
|
+
mcpResources,
|
|
298
|
+
options,
|
|
299
|
+
credentials
|
|
300
|
+
);
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Build a server for custom MCP hosts. Use surface() for protocol-aware stdio.
|
|
305
|
+
*
|
|
306
|
+
* Derivation failures throw at this host bootstrap boundary after
|
|
307
|
+
* deriveMcpTools has represented the framework failure as a Result.
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* ```ts
|
|
311
|
+
* const server = createServer(graph, { name: 'demo' });
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
314
|
+
export const createServer = (
|
|
315
|
+
graph: Topo,
|
|
316
|
+
options: CreateServerOptions = {}
|
|
317
|
+
): Server => createServerFactory(graph, options)();
|
package/src/stdio.ts
CHANGED
|
@@ -1,25 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin wrapper around MCP SDK's StdioServerTransport.
|
|
3
|
-
*
|
|
4
|
-
* Exists as a separate function so it can be swapped for other transports
|
|
5
|
-
* (SSE, streamable HTTP) without changing surface().
|
|
6
|
-
*/
|
|
1
|
+
/** Protocol-aware MCP stdio serving through the official SDK. */
|
|
7
2
|
|
|
8
|
-
import type {
|
|
9
|
-
import {
|
|
3
|
+
import type { McpServerFactory } from '@modelcontextprotocol/server';
|
|
4
|
+
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
|
5
|
+
import type { StdioServerHandle } from '@modelcontextprotocol/server/stdio';
|
|
10
6
|
|
|
11
7
|
/**
|
|
12
|
-
*
|
|
8
|
+
* Serve stdio using a fresh server factory for protocol-era selection.
|
|
9
|
+
*
|
|
10
|
+
* The SDK may create a discovery probe before pinning a connection instance.
|
|
11
|
+
* Returning one previously connected server from the factory is unsupported.
|
|
13
12
|
*
|
|
14
13
|
* @example
|
|
15
14
|
* ```ts
|
|
16
15
|
* import { connectStdio, createServer } from '@ontrails/mcp';
|
|
17
16
|
*
|
|
18
|
-
* const
|
|
19
|
-
* await
|
|
17
|
+
* const connection = await connectStdio(() => createServer(graph));
|
|
18
|
+
* await connection.close();
|
|
20
19
|
* ```
|
|
21
20
|
*/
|
|
22
|
-
export const connectStdio = async (
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
};
|
|
21
|
+
export const connectStdio = async (
|
|
22
|
+
factory: McpServerFactory
|
|
23
|
+
): Promise<StdioServerHandle> => serveStdio(factory);
|