@saturn-universe/tools 0.0.0-stage → 0.1.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.
- package/LICENSE +661 -0
- package/dist/container-sandbox.d.ts +168 -0
- package/dist/container-sandbox.js +1241 -0
- package/dist/counter.d.ts +5 -0
- package/dist/counter.js +82 -0
- package/dist/data-review.d.ts +4 -0
- package/dist/data-review.js +146 -0
- package/dist/execution-backend.d.ts +55 -0
- package/dist/execution-backend.js +339 -0
- package/dist/executor.d.ts +25 -0
- package/dist/executor.js +978 -0
- package/dist/file-window.d.ts +3 -0
- package/dist/file-window.js +12 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +17 -0
- package/dist/mcp-headers.d.ts +3 -0
- package/dist/mcp-headers.js +51 -0
- package/dist/mcp-http.d.ts +3 -0
- package/dist/mcp-http.js +253 -0
- package/dist/mcp-stdio.d.ts +2 -0
- package/dist/mcp-stdio.js +147 -0
- package/dist/mcp-wire.d.ts +33 -0
- package/dist/mcp-wire.js +85 -0
- package/dist/mcp.d.ts +19 -0
- package/dist/mcp.js +325 -0
- package/dist/path-containment.d.ts +3 -0
- package/dist/path-containment.js +11 -0
- package/dist/planner.d.ts +3 -0
- package/dist/planner.js +162 -0
- package/dist/process-manager.d.ts +67 -0
- package/dist/process-manager.js +423 -0
- package/dist/process-output.d.ts +34 -0
- package/dist/process-output.js +162 -0
- package/dist/process-worker.d.ts +1 -0
- package/dist/process-worker.js +202 -0
- package/dist/registry.d.ts +33 -0
- package/dist/registry.js +227 -0
- package/dist/search.d.ts +9 -0
- package/dist/search.js +96 -0
- package/dist/team.d.ts +36 -0
- package/dist/team.js +284 -0
- package/dist/text-patch.d.ts +15 -0
- package/dist/text-patch.js +81 -0
- package/dist/todo.d.ts +3 -0
- package/dist/todo.js +105 -0
- package/dist/workspace-discovery.d.ts +42 -0
- package/dist/workspace-discovery.js +404 -0
- package/dist/workspace-snapshot.d.ts +28 -0
- package/dist/workspace-snapshot.js +371 -0
- package/dist/workspace.d.ts +22 -0
- package/dist/workspace.js +1819 -0
- package/package.json +16 -3
- package/README.md +0 -3
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Reads up to length bytes at an absolute offset without advancing the handle's cursor. */
|
|
2
|
+
export async function readFileWindow(handle, offset, length) {
|
|
3
|
+
const buffer = Buffer.alloc(length);
|
|
4
|
+
let read = 0;
|
|
5
|
+
while (read < length) {
|
|
6
|
+
const { bytesRead } = await handle.read(buffer, read, length - read, offset + read);
|
|
7
|
+
if (!bytesRead)
|
|
8
|
+
break;
|
|
9
|
+
read += bytesRead;
|
|
10
|
+
}
|
|
11
|
+
return buffer.subarray(0, read);
|
|
12
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export { Registry } from './registry.js';
|
|
2
|
+
export { createToolExecutor } from './executor.js';
|
|
3
|
+
export type { Executor, ExecutorDependencies } from './executor.js';
|
|
4
|
+
export { createCounterTool } from './counter.js';
|
|
5
|
+
export { createPlannerTool, plannerToolName } from './planner.js';
|
|
6
|
+
export { createExploreHypothesesTool, exploreHypothesesToolName } from './search.js';
|
|
7
|
+
export type { ExploreHypothesisInput } from './search.js';
|
|
8
|
+
export { createSpawnTeamTool, createTeamNotifyParentTool, spawnTeamToolName, teamNotifyParentToolName, } from './team.js';
|
|
9
|
+
export type { CreateSpawnTeamToolOptions, CreateTeamNotifyParentToolOptions, SpawnTeamCallerContext, TeamNotifyParentCallerContext, TeamNotifyParentDelivery, } from './team.js';
|
|
10
|
+
export { createTodoWriteTool, todoWriteToolName } from './todo.js';
|
|
11
|
+
export { createDataReviewTool, dataReviewToolName, dataReviewToolSet } from './data-review.js';
|
|
12
|
+
export type { TodoItem, TodoStatus } from '@saturn-universe/core';
|
|
13
|
+
export { createWorkspaceTools, containerReadonlyPrefix, maxShellTimeoutMs, outsideWorkspacePrefix, readonlyCommandAllowlist, } from './workspace.js';
|
|
14
|
+
export type { WorkspaceToolsOptions } from './workspace.js';
|
|
15
|
+
export { isContainedPath, relativePathWithin } from './path-containment.js';
|
|
16
|
+
export { readFileWindow } from './file-window.js';
|
|
17
|
+
export { assertSandboxPathContained, computeDirectoryBytes, createHostExecutionBackend, hostShellInvocation, runBoundedHostProcess, } from './execution-backend.js';
|
|
18
|
+
export type { ExecCommandInput, ExecutionBackend, ExecutionTarget, ResolvedExecutionContext, } from './execution-backend.js';
|
|
19
|
+
export { buildDockerRunArgs, buildTargetDockerRunArgs, CONTAINER_PROCESS_LAUNCH_SCRIPT, CONTAINER_PROCESS_STOP_SCRIPT, containerPathToHostPath, createContainerSandboxBackend, createDockerContainerRunner, DEFAULT_ALLOWED_TARGET_CAPABILITIES, dockerClientEnvironment, hostPathToContainerPath, normalizeReadonlyContainerPath, validateReadonlyMount, validateTargetCapabilities, validateTargetName, validateTargetSeedFilePath, } from './container-sandbox.js';
|
|
20
|
+
export type { ContainerBackendKind, ContainerCaptureResult, ContainerExecStreamOptions, ContainerExecStreamResult, ContainerInspectState, ContainerLogsResult, ContainerRunner, ContainerSandboxBackendOptions, ContainerSandboxSession, ContainerStartSpec, ManagedContainerInfo, ManagedNetworkInfo, TargetContainerStartSpec, TargetSeedMount, } from './container-sandbox.js';
|
|
21
|
+
export { createProcessManager } from './process-manager.js';
|
|
22
|
+
export type { ProcessManager, ProcessManagerOptions, ProcessScope, ProcessStartInput, ProcessStopCommand, ProcessReadOptions, ProcessSnapshot, } from './process-manager.js';
|
|
23
|
+
export { createWorkspaceSnapshotManager, defaultMaxBranchCopyBytes, isManagedBranchWorkspace, } from './workspace-snapshot.js';
|
|
24
|
+
export type { BranchWorkspaceHandle, BranchWorkspaceKind, BranchWorkspaceMode, CreateBranchWorkspaceInput, WorkspaceSnapshotManager, } from './workspace-snapshot.js';
|
|
25
|
+
export { openMcpServer } from './mcp.js';
|
|
26
|
+
export { McpError } from './mcp-wire.js';
|
|
27
|
+
export type { McpServerConfig } from './mcp.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { Registry } from './registry.js';
|
|
2
|
+
export { createToolExecutor } from './executor.js';
|
|
3
|
+
export { createCounterTool } from './counter.js';
|
|
4
|
+
export { createPlannerTool, plannerToolName } from './planner.js';
|
|
5
|
+
export { createExploreHypothesesTool, exploreHypothesesToolName } from './search.js';
|
|
6
|
+
export { createSpawnTeamTool, createTeamNotifyParentTool, spawnTeamToolName, teamNotifyParentToolName, } from './team.js';
|
|
7
|
+
export { createTodoWriteTool, todoWriteToolName } from './todo.js';
|
|
8
|
+
export { createDataReviewTool, dataReviewToolName, dataReviewToolSet } from './data-review.js';
|
|
9
|
+
export { createWorkspaceTools, containerReadonlyPrefix, maxShellTimeoutMs, outsideWorkspacePrefix, readonlyCommandAllowlist, } from './workspace.js';
|
|
10
|
+
export { isContainedPath, relativePathWithin } from './path-containment.js';
|
|
11
|
+
export { readFileWindow } from './file-window.js';
|
|
12
|
+
export { assertSandboxPathContained, computeDirectoryBytes, createHostExecutionBackend, hostShellInvocation, runBoundedHostProcess, } from './execution-backend.js';
|
|
13
|
+
export { buildDockerRunArgs, buildTargetDockerRunArgs, CONTAINER_PROCESS_LAUNCH_SCRIPT, CONTAINER_PROCESS_STOP_SCRIPT, containerPathToHostPath, createContainerSandboxBackend, createDockerContainerRunner, DEFAULT_ALLOWED_TARGET_CAPABILITIES, dockerClientEnvironment, hostPathToContainerPath, normalizeReadonlyContainerPath, validateReadonlyMount, validateTargetCapabilities, validateTargetName, validateTargetSeedFilePath, } from './container-sandbox.js';
|
|
14
|
+
export { createProcessManager } from './process-manager.js';
|
|
15
|
+
export { createWorkspaceSnapshotManager, defaultMaxBranchCopyBytes, isManagedBranchWorkspace, } from './workspace-snapshot.js';
|
|
16
|
+
export { openMcpServer } from './mcp.js';
|
|
17
|
+
export { McpError } from './mcp-wire.js';
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { headerValue } from './mcp-http.js';
|
|
2
|
+
import { McpError, object } from './mcp-wire.js';
|
|
3
|
+
export function parameterHeaders(schema) {
|
|
4
|
+
const locations = new Map();
|
|
5
|
+
function visit(node, path, depth) {
|
|
6
|
+
if (depth > 48)
|
|
7
|
+
throw new McpError('MCP schema nesting exceeds limit');
|
|
8
|
+
if (!node || typeof node !== 'object')
|
|
9
|
+
return;
|
|
10
|
+
if (Array.isArray(node)) {
|
|
11
|
+
for (const value of node)
|
|
12
|
+
visit(value, undefined, depth + 1);
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (!object(node))
|
|
16
|
+
return;
|
|
17
|
+
if ('x-mcp-header' in node) {
|
|
18
|
+
const name = node['x-mcp-header'];
|
|
19
|
+
if (typeof name !== 'string' ||
|
|
20
|
+
!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(name) ||
|
|
21
|
+
!path?.length ||
|
|
22
|
+
locations.has(name.toLowerCase()) ||
|
|
23
|
+
(node.type !== 'string' && node.type !== 'integer' && node.type !== 'boolean'))
|
|
24
|
+
throw new McpError('Invalid MCP parameter header definition');
|
|
25
|
+
locations.set(name.toLowerCase(), { path, type: node.type });
|
|
26
|
+
}
|
|
27
|
+
for (const [key, value] of Object.entries(node)) {
|
|
28
|
+
if (key === 'properties' && object(value)) {
|
|
29
|
+
for (const [property, child] of Object.entries(value))
|
|
30
|
+
visit(child, path && [...path, property], depth + 1);
|
|
31
|
+
}
|
|
32
|
+
else
|
|
33
|
+
visit(value, undefined, depth + 1);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
visit(schema, [], 0);
|
|
37
|
+
return (input) => {
|
|
38
|
+
const headers = {};
|
|
39
|
+
for (const [name, { path, type }] of locations) {
|
|
40
|
+
let value = input;
|
|
41
|
+
for (const key of path)
|
|
42
|
+
value = object(value) && Object.hasOwn(value, key) ? value[key] : undefined;
|
|
43
|
+
if (value === null || value === undefined)
|
|
44
|
+
continue;
|
|
45
|
+
if (type === 'integer' ? !Number.isSafeInteger(value) : typeof value !== type)
|
|
46
|
+
throw new McpError('Invalid MCP parameter header value');
|
|
47
|
+
headers['Mcp-Param-' + name] = headerValue(String(value));
|
|
48
|
+
}
|
|
49
|
+
return headers;
|
|
50
|
+
};
|
|
51
|
+
}
|
package/dist/mcp-http.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { McpError, decodeMessage, encode, maxMessageBytes, modernVersion, object, requestMessage, responseResult, serverReply, } from './mcp-wire.js';
|
|
2
|
+
// Only include recognized schemes and machine-readable codes. Challenge parameters
|
|
3
|
+
// and server-provided messages can contain credentials or arbitrary text.
|
|
4
|
+
const authSchemes = ['Bearer', 'Basic', 'Digest', 'Negotiate', 'DPoP', 'Mutual', 'AWS4-HMAC-SHA256'];
|
|
5
|
+
const httpErrorCodes = new Set([
|
|
6
|
+
'invalid_request',
|
|
7
|
+
'invalid_token',
|
|
8
|
+
'expired_token',
|
|
9
|
+
'missing_token',
|
|
10
|
+
'insufficient_scope',
|
|
11
|
+
'invalid_client',
|
|
12
|
+
'access_denied',
|
|
13
|
+
'unauthorized',
|
|
14
|
+
'forbidden',
|
|
15
|
+
'invalid_grant',
|
|
16
|
+
'server_error',
|
|
17
|
+
'temporarily_unavailable',
|
|
18
|
+
]);
|
|
19
|
+
async function httpFailure(response, stage) {
|
|
20
|
+
const status = response.status;
|
|
21
|
+
const auth = status === 401 || status === 403;
|
|
22
|
+
const challenge = response.headers.get('www-authenticate')?.trim().split(/\s|,/, 1)[0];
|
|
23
|
+
const scheme = authSchemes.find((item) => item.toLowerCase() === challenge?.toLowerCase());
|
|
24
|
+
let payload;
|
|
25
|
+
if (response.body) {
|
|
26
|
+
const reader = response.body.getReader();
|
|
27
|
+
try {
|
|
28
|
+
if (response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() === 'application/json') {
|
|
29
|
+
const timeout = AbortSignal.timeout(500);
|
|
30
|
+
const cancel = () => void reader.cancel().catch(() => { });
|
|
31
|
+
timeout.addEventListener('abort', cancel, { once: true });
|
|
32
|
+
try {
|
|
33
|
+
let text = '';
|
|
34
|
+
let size = 0;
|
|
35
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
36
|
+
for (;;) {
|
|
37
|
+
const { done, value } = await reader.read();
|
|
38
|
+
size += value?.length ?? 0;
|
|
39
|
+
if (size > 4096 || timeout.aborted)
|
|
40
|
+
break;
|
|
41
|
+
text += decoder.decode(value, { stream: !done });
|
|
42
|
+
if (done) {
|
|
43
|
+
payload = JSON.parse(text);
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
timeout.removeEventListener('abort', cancel);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// Preserve the HTTP failure if the optional diagnostic cannot be read.
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
void reader.cancel().catch(() => { });
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const field = object(payload) ? payload.error : undefined;
|
|
62
|
+
const code = typeof field === 'string' && httpErrorCodes.has(field) ? field : undefined;
|
|
63
|
+
const rpcCode = !auth && object(payload) && payload.jsonrpc === '2.0' && object(field) && Number.isSafeInteger(field.code)
|
|
64
|
+
? field.code
|
|
65
|
+
: undefined;
|
|
66
|
+
const summary = [stage, `HTTP ${status}`, scheme, code].filter(Boolean).join(' · ');
|
|
67
|
+
return new McpError(summary, rpcCode, status, stage, scheme, code);
|
|
68
|
+
}
|
|
69
|
+
export function httpTransport(address, customHeaders) {
|
|
70
|
+
const url = new URL(address);
|
|
71
|
+
if (url.username ||
|
|
72
|
+
url.password ||
|
|
73
|
+
url.hash ||
|
|
74
|
+
!(url.protocol === 'https:' ||
|
|
75
|
+
(url.protocol === 'http:' &&
|
|
76
|
+
(url.hostname === 'localhost' ||
|
|
77
|
+
url.hostname === '[::1]' ||
|
|
78
|
+
(/^127\./.test(url.hostname) && /^\d+\.\d+\.\d+\.\d+$/.test(url.hostname))))))
|
|
79
|
+
throw new McpError('MCP endpoint requires HTTPS or loopback HTTP');
|
|
80
|
+
const lifetime = new AbortController();
|
|
81
|
+
let session;
|
|
82
|
+
let nextId = 0;
|
|
83
|
+
let pending = 0;
|
|
84
|
+
let closePromise;
|
|
85
|
+
const sanitizedHeaders = {};
|
|
86
|
+
if (customHeaders) {
|
|
87
|
+
for (const [key, value] of Object.entries(customHeaders)) {
|
|
88
|
+
if (/^[A-Za-z0-9-]+$/.test(key) && typeof value === 'string' && !/[\r\n\0]/.test(value)) {
|
|
89
|
+
sanitizedHeaders[key] = value;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function headers(message) {
|
|
94
|
+
const result = {
|
|
95
|
+
...sanitizedHeaders,
|
|
96
|
+
accept: 'application/json, text/event-stream',
|
|
97
|
+
'content-type': 'application/json',
|
|
98
|
+
};
|
|
99
|
+
if (session)
|
|
100
|
+
result['Mcp-Session-Id'] = session;
|
|
101
|
+
if (message?.method !== 'initialize')
|
|
102
|
+
result['Mcp-Protocol-Version'] = transport.version;
|
|
103
|
+
if (transport.version === modernVersion && typeof message?.method === 'string') {
|
|
104
|
+
result['Mcp-Method'] = message.method;
|
|
105
|
+
if (message.method === 'tools/call' &&
|
|
106
|
+
object(message.params) &&
|
|
107
|
+
typeof message.params.name === 'string')
|
|
108
|
+
result['Mcp-Name'] = headerValue(message.params.name);
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
async function post(message, signal, extra) {
|
|
113
|
+
return fetch(url, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
redirect: 'error',
|
|
116
|
+
headers: { ...headers(message), ...extra },
|
|
117
|
+
body: encode(message),
|
|
118
|
+
signal: AbortSignal.any([signal, lifetime.signal]),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
async function sendOneWay(message, signal) {
|
|
122
|
+
const response = await post(message, signal);
|
|
123
|
+
const stage = String(message.method);
|
|
124
|
+
if (!response.ok)
|
|
125
|
+
throw await httpFailure(response, stage);
|
|
126
|
+
await response.body?.cancel();
|
|
127
|
+
if (response.status !== 202)
|
|
128
|
+
throw new McpError('MCP notification refused', undefined, response.status, stage);
|
|
129
|
+
}
|
|
130
|
+
const transport = {
|
|
131
|
+
version: modernVersion,
|
|
132
|
+
changed: false,
|
|
133
|
+
async request(method, params, signal, extra) {
|
|
134
|
+
signal.throwIfAborted();
|
|
135
|
+
if (pending >= 32)
|
|
136
|
+
throw new McpError('Too many pending MCP requests');
|
|
137
|
+
pending++;
|
|
138
|
+
const id = ++nextId;
|
|
139
|
+
const abort = () => {
|
|
140
|
+
if (transport.version !== modernVersion && method !== 'initialize' && !lifetime.signal.aborted)
|
|
141
|
+
void transport
|
|
142
|
+
.notify('notifications/cancelled', { requestId: id }, AbortSignal.timeout(1000))
|
|
143
|
+
.catch(() => { });
|
|
144
|
+
};
|
|
145
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
146
|
+
try {
|
|
147
|
+
const response = await post(requestMessage(transport.version, id, method, params), signal, extra);
|
|
148
|
+
if (response.status === 404 && session)
|
|
149
|
+
transport.changed = true;
|
|
150
|
+
if (!response.ok)
|
|
151
|
+
throw await httpFailure(response, method);
|
|
152
|
+
const media = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
153
|
+
if (method === 'initialize') {
|
|
154
|
+
const assigned = response.headers.get('mcp-session-id');
|
|
155
|
+
if (assigned !== null && !/^[\x21-\x7e]{1,512}$/.test(assigned)) {
|
|
156
|
+
await response.body?.cancel();
|
|
157
|
+
throw new McpError('Invalid MCP session id', undefined, response.status, method);
|
|
158
|
+
}
|
|
159
|
+
session = assigned ?? undefined;
|
|
160
|
+
}
|
|
161
|
+
if (!response.body || (media !== 'application/json' && media !== 'text/event-stream')) {
|
|
162
|
+
await response.body?.cancel();
|
|
163
|
+
throw new McpError('Unsupported MCP response', undefined, response.status, method);
|
|
164
|
+
}
|
|
165
|
+
const streamed = media === 'text/event-stream';
|
|
166
|
+
const reader = response.body.getReader();
|
|
167
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
168
|
+
let size = 0;
|
|
169
|
+
let buffer = '';
|
|
170
|
+
try {
|
|
171
|
+
while (true) {
|
|
172
|
+
const { done, value } = await reader.read();
|
|
173
|
+
size += value?.length ?? 0;
|
|
174
|
+
if (size > maxMessageBytes)
|
|
175
|
+
throw new McpError('Oversized MCP response');
|
|
176
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
177
|
+
if (streamed) {
|
|
178
|
+
for (let end; (end = /\r\n\r\n|\n\r\n|\r\n\n|\n\n|\r\r/.exec(buffer));) {
|
|
179
|
+
const frame = buffer.slice(0, end.index);
|
|
180
|
+
buffer = buffer.slice(end.index + end[0].length);
|
|
181
|
+
const data = frame
|
|
182
|
+
.split(/\r\n|\n|\r/)
|
|
183
|
+
.filter((line) => line.startsWith('data:'))
|
|
184
|
+
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
185
|
+
.join('\n');
|
|
186
|
+
if (!data)
|
|
187
|
+
continue;
|
|
188
|
+
const reply = decodeMessage(data);
|
|
189
|
+
if ('method' in reply) {
|
|
190
|
+
if (reply.method === 'notifications/tools/list_changed')
|
|
191
|
+
transport.changed = true;
|
|
192
|
+
const answer = serverReply(reply);
|
|
193
|
+
if (answer && transport.version !== modernVersion)
|
|
194
|
+
await sendOneWay(answer, signal);
|
|
195
|
+
}
|
|
196
|
+
else
|
|
197
|
+
return responseResult(reply, id);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (done)
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
if (streamed)
|
|
204
|
+
throw new McpError('MCP stream ended before its result');
|
|
205
|
+
return responseResult(decodeMessage(buffer), id);
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (error instanceof McpError)
|
|
209
|
+
throw new McpError(error.message, error.rpcCode, response.status, method);
|
|
210
|
+
if (error instanceof TypeError && !signal.aborted)
|
|
211
|
+
throw new McpError('Invalid MCP HTTP response', undefined, response.status, method);
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
await reader.cancel().catch(() => { });
|
|
216
|
+
reader.releaseLock();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
signal.removeEventListener('abort', abort);
|
|
221
|
+
pending--;
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
notify(method, params, signal) {
|
|
225
|
+
return sendOneWay({ jsonrpc: '2.0', method, params }, signal);
|
|
226
|
+
},
|
|
227
|
+
close() {
|
|
228
|
+
return (closePromise ??= (async () => {
|
|
229
|
+
lifetime.abort();
|
|
230
|
+
if (session) {
|
|
231
|
+
try {
|
|
232
|
+
const response = await fetch(url, {
|
|
233
|
+
method: 'DELETE',
|
|
234
|
+
headers: headers(),
|
|
235
|
+
redirect: 'error',
|
|
236
|
+
signal: AbortSignal.timeout(1000),
|
|
237
|
+
});
|
|
238
|
+
await response.body?.cancel();
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
// The remote process may already have closed its session.
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
})());
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
return transport;
|
|
248
|
+
}
|
|
249
|
+
export function headerValue(value) {
|
|
250
|
+
if (/^[\x20-\x7e]*$/.test(value) && value.trim() === value && !/^=\?base64\?.*\?=$/.test(value))
|
|
251
|
+
return value;
|
|
252
|
+
return '=?base64?' + Buffer.from(value).toString('base64') + '?=';
|
|
253
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { McpError, decodeMessage, encode, maxMessageBytes, modernVersion, requestMessage, responseResult, serverReply, } from './mcp-wire.js';
|
|
3
|
+
export function stdioTransport(command, args, cwd, customEnv) {
|
|
4
|
+
const env = {};
|
|
5
|
+
for (const key of ['PATH', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'LANG'])
|
|
6
|
+
if (process.env[key] !== undefined)
|
|
7
|
+
env[key] = process.env[key];
|
|
8
|
+
if (customEnv) {
|
|
9
|
+
for (const [key, value] of Object.entries(customEnv)) {
|
|
10
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === 'string' && !value.includes('\0')) {
|
|
11
|
+
env[key] = value;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const child = spawn(command, args, {
|
|
16
|
+
cwd,
|
|
17
|
+
env,
|
|
18
|
+
shell: false,
|
|
19
|
+
windowsHide: true,
|
|
20
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
21
|
+
});
|
|
22
|
+
const pending = new Map();
|
|
23
|
+
let nextId = 0;
|
|
24
|
+
let failed = false;
|
|
25
|
+
let closePromise;
|
|
26
|
+
const exited = new Promise((resolve) => child.once('close', () => resolve()));
|
|
27
|
+
function fail() {
|
|
28
|
+
if (failed)
|
|
29
|
+
return;
|
|
30
|
+
failed = true;
|
|
31
|
+
transport.changed = true;
|
|
32
|
+
for (const waiter of pending.values())
|
|
33
|
+
waiter.reject(new McpError('MCP server disconnected'));
|
|
34
|
+
pending.clear();
|
|
35
|
+
child.stdin.destroy();
|
|
36
|
+
child.stdout.destroy();
|
|
37
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
38
|
+
child.kill('SIGKILL');
|
|
39
|
+
}
|
|
40
|
+
child.on('error', fail);
|
|
41
|
+
child.stdin.on('error', fail);
|
|
42
|
+
child.stdout.on('error', fail);
|
|
43
|
+
child.once('close', fail);
|
|
44
|
+
function write(message) {
|
|
45
|
+
if (failed || closePromise || !child.stdin.writable)
|
|
46
|
+
throw new McpError('MCP server unavailable');
|
|
47
|
+
const line = encode(message) + '\n';
|
|
48
|
+
if (child.stdin.writableLength + Buffer.byteLength(line) > maxMessageBytes * 2)
|
|
49
|
+
throw new McpError('MCP write queue full');
|
|
50
|
+
child.stdin.write(line);
|
|
51
|
+
}
|
|
52
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
53
|
+
let fragments = [];
|
|
54
|
+
let size = 0;
|
|
55
|
+
child.stdout.on('data', (chunk) => {
|
|
56
|
+
try {
|
|
57
|
+
let offset = 0;
|
|
58
|
+
while (offset < chunk.length) {
|
|
59
|
+
const end = chunk.indexOf(10, offset);
|
|
60
|
+
const part = chunk.subarray(offset, end < 0 ? chunk.length : end);
|
|
61
|
+
size += part.length;
|
|
62
|
+
if (size > maxMessageBytes)
|
|
63
|
+
throw new McpError('Oversized MCP line');
|
|
64
|
+
fragments.push(part);
|
|
65
|
+
if (end < 0)
|
|
66
|
+
break;
|
|
67
|
+
const message = decodeMessage(decoder.decode(Buffer.concat(fragments, size)));
|
|
68
|
+
fragments = [];
|
|
69
|
+
size = 0;
|
|
70
|
+
offset = end + 1;
|
|
71
|
+
if (typeof message.method === 'string') {
|
|
72
|
+
if (message.method === 'notifications/tools/list_changed')
|
|
73
|
+
transport.changed = true;
|
|
74
|
+
const reply = serverReply(message);
|
|
75
|
+
if (reply)
|
|
76
|
+
write(reply);
|
|
77
|
+
}
|
|
78
|
+
else if (typeof message.id === 'number') {
|
|
79
|
+
pending.get(message.id)?.receive(message);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
throw new McpError('Invalid MCP response id');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
fail();
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
const transport = {
|
|
91
|
+
version: modernVersion,
|
|
92
|
+
changed: false,
|
|
93
|
+
async request(method, params, signal) {
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
if (pending.size >= 32)
|
|
96
|
+
throw new McpError('Too many pending MCP requests');
|
|
97
|
+
const id = ++nextId;
|
|
98
|
+
const reply = await new Promise((resolve, reject) => {
|
|
99
|
+
const abort = () => {
|
|
100
|
+
try {
|
|
101
|
+
if (method !== 'initialize')
|
|
102
|
+
write({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id } });
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// The process may have exited before cancellation was delivered.
|
|
106
|
+
}
|
|
107
|
+
reject(signal.reason);
|
|
108
|
+
};
|
|
109
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
110
|
+
pending.set(id, {
|
|
111
|
+
receive(message) {
|
|
112
|
+
signal.removeEventListener('abort', abort);
|
|
113
|
+
resolve(message);
|
|
114
|
+
},
|
|
115
|
+
reject(error) {
|
|
116
|
+
signal.removeEventListener('abort', abort);
|
|
117
|
+
reject(error);
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
write(requestMessage(transport.version, id, method, params));
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
pending.get(id).reject(error);
|
|
125
|
+
}
|
|
126
|
+
}).finally(() => pending.delete(id));
|
|
127
|
+
return responseResult(reply, id);
|
|
128
|
+
},
|
|
129
|
+
async notify(method, params, signal) {
|
|
130
|
+
signal.throwIfAborted();
|
|
131
|
+
write({ jsonrpc: '2.0', method, params });
|
|
132
|
+
},
|
|
133
|
+
close() {
|
|
134
|
+
return (closePromise ??= (async () => {
|
|
135
|
+
child.stdin.end();
|
|
136
|
+
const timer = setTimeout(fail, 250);
|
|
137
|
+
try {
|
|
138
|
+
await exited;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
}
|
|
143
|
+
})());
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
return transport;
|
|
147
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { JsonValue } from '@saturn-universe/core';
|
|
2
|
+
export declare const modernVersion = "2026-07-28";
|
|
3
|
+
export declare const maxMessageBytes: number;
|
|
4
|
+
export type Fields = Record<string, JsonValue>;
|
|
5
|
+
export type RpcMessage = Fields & {
|
|
6
|
+
jsonrpc: '2.0';
|
|
7
|
+
};
|
|
8
|
+
export declare function object(value: unknown): value is Fields;
|
|
9
|
+
export declare class McpError extends Error {
|
|
10
|
+
readonly rpcCode?: number | undefined;
|
|
11
|
+
readonly httpStatus?: number | undefined;
|
|
12
|
+
readonly stage?: string | undefined;
|
|
13
|
+
readonly authScheme?: string | undefined;
|
|
14
|
+
readonly errorCode?: string | undefined;
|
|
15
|
+
readonly kind: 'auth_required' | 'forbidden' | 'http_error' | 'protocol_error';
|
|
16
|
+
constructor(message: string, rpcCode?: number | undefined, httpStatus?: number | undefined, stage?: string | undefined, authScheme?: string | undefined, errorCode?: string | undefined);
|
|
17
|
+
}
|
|
18
|
+
export declare function decodeMessage(text: string): RpcMessage;
|
|
19
|
+
export declare function responseResult(message: RpcMessage, id: number, status?: number): Fields;
|
|
20
|
+
export interface McpTransport {
|
|
21
|
+
version: string;
|
|
22
|
+
changed: boolean;
|
|
23
|
+
request(method: string, params: Fields, signal: AbortSignal, headers?: Record<string, string>): Promise<Fields>;
|
|
24
|
+
notify(method: string, params: Fields, signal: AbortSignal): Promise<void>;
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
export declare const clientInfo: {
|
|
28
|
+
name: string;
|
|
29
|
+
version: string;
|
|
30
|
+
};
|
|
31
|
+
export declare function requestMessage(version: string, id: number, method: string, params: Fields): RpcMessage;
|
|
32
|
+
export declare function encode(message: RpcMessage): string;
|
|
33
|
+
export declare function serverReply(message: RpcMessage): RpcMessage | undefined;
|
package/dist/mcp-wire.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export const modernVersion = '2026-07-28';
|
|
2
|
+
export const maxMessageBytes = 512 * 1024;
|
|
3
|
+
export function object(value) {
|
|
4
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
export class McpError extends Error {
|
|
7
|
+
rpcCode;
|
|
8
|
+
httpStatus;
|
|
9
|
+
stage;
|
|
10
|
+
authScheme;
|
|
11
|
+
errorCode;
|
|
12
|
+
kind;
|
|
13
|
+
constructor(message, rpcCode, httpStatus, stage, authScheme, errorCode) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.rpcCode = rpcCode;
|
|
16
|
+
this.httpStatus = httpStatus;
|
|
17
|
+
this.stage = stage;
|
|
18
|
+
this.authScheme = authScheme;
|
|
19
|
+
this.errorCode = errorCode;
|
|
20
|
+
this.kind =
|
|
21
|
+
httpStatus === 401
|
|
22
|
+
? 'auth_required'
|
|
23
|
+
: httpStatus === 403
|
|
24
|
+
? 'forbidden'
|
|
25
|
+
: httpStatus !== undefined && (httpStatus < 200 || httpStatus >= 300)
|
|
26
|
+
? 'http_error'
|
|
27
|
+
: 'protocol_error';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export function decodeMessage(text) {
|
|
31
|
+
let value;
|
|
32
|
+
try {
|
|
33
|
+
value = JSON.parse(text);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new McpError('Invalid MCP JSON');
|
|
37
|
+
}
|
|
38
|
+
if (!object(value) || value.jsonrpc !== '2.0')
|
|
39
|
+
throw new McpError('Invalid MCP envelope');
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
export function responseResult(message, id, status) {
|
|
43
|
+
if (message.id !== id ||
|
|
44
|
+
'method' in message ||
|
|
45
|
+
Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error'))
|
|
46
|
+
throw new McpError('Invalid MCP response', undefined, status);
|
|
47
|
+
if (object(message.error) && typeof message.error.code === 'number')
|
|
48
|
+
throw new McpError('MCP request failed', message.error.code, status);
|
|
49
|
+
if (!object(message.result))
|
|
50
|
+
throw new McpError('Invalid MCP result', undefined, status);
|
|
51
|
+
return message.result;
|
|
52
|
+
}
|
|
53
|
+
export const clientInfo = { name: 'saturn', version: '1' };
|
|
54
|
+
export function requestMessage(version, id, method, params) {
|
|
55
|
+
return {
|
|
56
|
+
jsonrpc: '2.0',
|
|
57
|
+
id,
|
|
58
|
+
method,
|
|
59
|
+
params: version === modernVersion
|
|
60
|
+
? {
|
|
61
|
+
...params,
|
|
62
|
+
_meta: {
|
|
63
|
+
'io.modelcontextprotocol/protocolVersion': version,
|
|
64
|
+
'io.modelcontextprotocol/clientInfo': clientInfo,
|
|
65
|
+
'io.modelcontextprotocol/clientCapabilities': {},
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
: params,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function encode(message) {
|
|
72
|
+
const text = JSON.stringify(message);
|
|
73
|
+
if (Buffer.byteLength(text) > maxMessageBytes)
|
|
74
|
+
throw new McpError('MCP message exceeds the size limit');
|
|
75
|
+
return text;
|
|
76
|
+
}
|
|
77
|
+
export function serverReply(message) {
|
|
78
|
+
if (typeof message.method !== 'string' || !('id' in message))
|
|
79
|
+
return;
|
|
80
|
+
if (typeof message.id !== 'number' && typeof message.id !== 'string')
|
|
81
|
+
throw new McpError('Invalid MCP server request id');
|
|
82
|
+
return message.method === 'ping'
|
|
83
|
+
? { jsonrpc: '2.0', id: message.id, result: {} }
|
|
84
|
+
: { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Unsupported client method' } };
|
|
85
|
+
}
|