@wincode/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -2
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +34 -4
- package/src/client.ts +370 -0
- package/src/config/resolve.ts +722 -0
- package/src/config/schema.ts +96 -0
- package/src/config.ts +31 -0
- package/src/identifiers.ts +6 -0
- package/src/index.ts +10 -0
- package/src/management.ts +257 -0
- package/src/manifest.ts +102 -0
- package/src/oauth.ts +347 -0
- package/src/plugin/config.ts +40 -0
- package/src/plugin/index.ts +501 -0
- package/src/registry.ts +1455 -0
- package/src/result.ts +504 -0
- package/src/sanitize.ts +32 -0
- package/src/tool-identity.ts +24 -0
- package/src/utf8-byte-length.ts +4 -0
- package/test/client.test.ts +642 -0
- package/test/config-resolve.test.ts +376 -0
- package/test/management.test.ts +186 -0
- package/test/manifest.test.ts +17 -0
- package/test/oauth.test.ts +106 -0
- package/test/plugin-config.test.ts +117 -0
- package/test/result.test.ts +291 -0
- package/test/sanitize.test.ts +103 -0
- package/test/tool-identity.test.ts +27 -0
- package/tsconfig.json +15 -0
package/src/result.ts
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { ToolCallOutput } from "@wincode/agent-core";
|
|
5
|
+
import {
|
|
6
|
+
isArray,
|
|
7
|
+
isBoolean,
|
|
8
|
+
isNull,
|
|
9
|
+
isNumber,
|
|
10
|
+
isPlainObject,
|
|
11
|
+
isString,
|
|
12
|
+
isUndefined,
|
|
13
|
+
} from "@wincode/utils";
|
|
14
|
+
import type { JsonValue } from "type-fest";
|
|
15
|
+
import type { McpClientResourceContent } from "./client";
|
|
16
|
+
import { MAX_MCP_RESULT_BYTES } from "./manifest";
|
|
17
|
+
import type { McpCatalogSnapshot } from "./registry";
|
|
18
|
+
import { utf8ByteLength } from "./utf8-byte-length";
|
|
19
|
+
|
|
20
|
+
export type { JsonValue } from "type-fest";
|
|
21
|
+
|
|
22
|
+
export type McpNormalizedResult = {
|
|
23
|
+
content: JsonValue[];
|
|
24
|
+
isError: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Marks a result authored by the registry itself (stale snapshot, unknown
|
|
27
|
+
* tool, registry rejection, disabled server, sanitized execution failure) so
|
|
28
|
+
* callers may surface that text verbatim. Results produced by an MCP server
|
|
29
|
+
* are untrusted tool content and carry no owner; callers must not surface
|
|
30
|
+
* their text through an error path.
|
|
31
|
+
*/
|
|
32
|
+
owner?: "registry";
|
|
33
|
+
structuredContent?: JsonValue;
|
|
34
|
+
truncated: boolean;
|
|
35
|
+
};
|
|
36
|
+
export type McpToolExecutor = (
|
|
37
|
+
snapshot: McpCatalogSnapshot,
|
|
38
|
+
toolName: string,
|
|
39
|
+
input: unknown,
|
|
40
|
+
signal?: AbortSignal
|
|
41
|
+
) => Promise<McpNormalizedResult>;
|
|
42
|
+
|
|
43
|
+
export type McpToolCallExecutor = (
|
|
44
|
+
snapshot: McpCatalogSnapshot,
|
|
45
|
+
toolName: string,
|
|
46
|
+
input: unknown,
|
|
47
|
+
signal?: AbortSignal
|
|
48
|
+
) => Promise<ToolCallOutput>;
|
|
49
|
+
|
|
50
|
+
export const createMcpToolExecutor = (
|
|
51
|
+
execute: McpToolExecutor | undefined
|
|
52
|
+
): McpToolCallExecutor | undefined => {
|
|
53
|
+
if (isUndefined(execute)) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
return async (snapshot, toolName, input, signal) => {
|
|
57
|
+
const result = await execute(snapshot, toolName, input, signal);
|
|
58
|
+
return result.isError
|
|
59
|
+
? { errorText: "MCP tool call failed.", type: "failure" }
|
|
60
|
+
: { output: result, type: "success" };
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
const MAX_ARTIFACT_BYTES = 16 * 1024 * 1024;
|
|
64
|
+
const MAX_INLINE_IMAGE_BYTES = 24 * 1024;
|
|
65
|
+
const MAX_INLINE_RESOURCE_TEXT_BYTES = 32 * 1024;
|
|
66
|
+
const MAX_RESOURCE_TEXT_PREVIEW_CHARS = 4096;
|
|
67
|
+
|
|
68
|
+
const size = (value: unknown): number => utf8ByteLength(JSON.stringify(value));
|
|
69
|
+
|
|
70
|
+
const writeArtifact = async (
|
|
71
|
+
content: Uint8Array | string,
|
|
72
|
+
extension: "bin" | "json" | "txt"
|
|
73
|
+
): Promise<string> => {
|
|
74
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "wincode-mcp-"));
|
|
75
|
+
const filePath = path.join(directory, `${crypto.randomUUID()}.${extension}`);
|
|
76
|
+
await fs.writeFile(filePath, content, { flag: "wx", mode: 0o600 });
|
|
77
|
+
return filePath;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const artifactText = async (
|
|
81
|
+
content: string,
|
|
82
|
+
mimeType: string
|
|
83
|
+
): Promise<string> => {
|
|
84
|
+
const preview = middleExcerpt(content, MAX_RESOURCE_TEXT_PREVIEW_CHARS);
|
|
85
|
+
if (utf8ByteLength(content) > MAX_ARTIFACT_BYTES) {
|
|
86
|
+
return `[MCP content ${mimeType} exceeds the 16 MiB artifact limit]\n\n${preview}`;
|
|
87
|
+
}
|
|
88
|
+
const filePath = await writeArtifact(content, "txt");
|
|
89
|
+
return `[MCP ${mimeType} content saved to ${filePath}]\n\n${preview}`;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const artifactBinary = async (
|
|
93
|
+
base64: string,
|
|
94
|
+
mimeType: string
|
|
95
|
+
): Promise<string> => {
|
|
96
|
+
const estimatedBytes = Math.floor((base64.length * 3) / 4);
|
|
97
|
+
if (estimatedBytes > MAX_ARTIFACT_BYTES) {
|
|
98
|
+
return `[MCP binary ${mimeType} content exceeds the 16 MiB artifact limit]`;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const bytes = Uint8Array.fromBase64(base64);
|
|
102
|
+
const filePath = await writeArtifact(bytes, "bin");
|
|
103
|
+
return `[MCP binary ${mimeType} content saved to ${filePath}]`;
|
|
104
|
+
} catch {
|
|
105
|
+
return `[MCP server returned invalid ${mimeType} base64 data]`;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const normalizeImageData = async (
|
|
110
|
+
data: string,
|
|
111
|
+
mimeType: string
|
|
112
|
+
): Promise<unknown> => {
|
|
113
|
+
const estimatedBytes = Math.floor((data.length * 3) / 4);
|
|
114
|
+
if (estimatedBytes <= MAX_INLINE_IMAGE_BYTES) {
|
|
115
|
+
return { type: "image", data, mimeType };
|
|
116
|
+
}
|
|
117
|
+
return { type: "text", text: await artifactBinary(data, mimeType) };
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const normalizeResourceBlob = async (
|
|
121
|
+
blob: string,
|
|
122
|
+
mimeType: string
|
|
123
|
+
): Promise<unknown> => {
|
|
124
|
+
const estimatedBytes = Math.floor((blob.length * 3) / 4);
|
|
125
|
+
if (
|
|
126
|
+
mimeType.startsWith("image/") &&
|
|
127
|
+
estimatedBytes <= MAX_INLINE_IMAGE_BYTES
|
|
128
|
+
) {
|
|
129
|
+
return { type: "image", data: blob, mimeType };
|
|
130
|
+
}
|
|
131
|
+
return { type: "text", text: await artifactBinary(blob, mimeType) };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const normalizeResourceContent = async (
|
|
135
|
+
item: Record<string, unknown>,
|
|
136
|
+
resource: Record<string, unknown>
|
|
137
|
+
): Promise<unknown> => {
|
|
138
|
+
const mimeType = bounded(stringValue(resource.mimeType));
|
|
139
|
+
if (isString(resource.text)) {
|
|
140
|
+
if (utf8ByteLength(resource.text) <= MAX_INLINE_RESOURCE_TEXT_BYTES) {
|
|
141
|
+
return item;
|
|
142
|
+
}
|
|
143
|
+
return { type: "text", text: await artifactText(resource.text, mimeType) };
|
|
144
|
+
}
|
|
145
|
+
if (isString(resource.blob)) {
|
|
146
|
+
return normalizeResourceBlob(resource.blob, mimeType);
|
|
147
|
+
}
|
|
148
|
+
return item;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const normalizeBinaryContent = async (
|
|
152
|
+
item: Record<string, unknown>
|
|
153
|
+
): Promise<unknown> => {
|
|
154
|
+
const mimeType = bounded(stringValue(item.mimeType));
|
|
155
|
+
if (item.type === "image" && isString(item.data)) {
|
|
156
|
+
return normalizeImageData(item.data, mimeType);
|
|
157
|
+
}
|
|
158
|
+
if (item.type === "audio" && isString(item.data)) {
|
|
159
|
+
return { type: "text", text: await artifactBinary(item.data, mimeType) };
|
|
160
|
+
}
|
|
161
|
+
if (item.type === "resource" && isPlainObject(item.resource)) {
|
|
162
|
+
return normalizeResourceContent(item, item.resource);
|
|
163
|
+
}
|
|
164
|
+
return item;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
export async function normalizeMcpResultWithArtifacts(
|
|
168
|
+
input: unknown
|
|
169
|
+
): Promise<McpNormalizedResult> {
|
|
170
|
+
const source = isPlainObject(input) ? input : {};
|
|
171
|
+
const content = isArray(source.content)
|
|
172
|
+
? await Promise.all(
|
|
173
|
+
source.content.map((item) =>
|
|
174
|
+
isPlainObject(item) ? normalizeBinaryContent(item) : item
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
: source.content;
|
|
178
|
+
const result = normalizeMcpResult({ ...source, content });
|
|
179
|
+
if (!result.truncated) {
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
const complete = safeJson(source);
|
|
183
|
+
let artifactMessage = "[MCP output exceeded the 16 MiB artifact limit]";
|
|
184
|
+
if (complete !== undefined) {
|
|
185
|
+
const serialized = JSON.stringify(complete);
|
|
186
|
+
if (utf8ByteLength(serialized) <= MAX_ARTIFACT_BYTES) {
|
|
187
|
+
const filePath = await writeArtifact(serialized, "json");
|
|
188
|
+
artifactMessage = `[Complete MCP output saved to ${filePath}]`;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const boundedResult = normalizeMcpResult({
|
|
192
|
+
content: [{ type: "text", text: artifactMessage }, ...result.content],
|
|
193
|
+
isError: result.isError,
|
|
194
|
+
structuredContent: result.structuredContent,
|
|
195
|
+
});
|
|
196
|
+
boundedResult.truncated = true;
|
|
197
|
+
return boundedResult;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export async function normalizeMcpResourceContents(
|
|
201
|
+
contents: readonly McpClientResourceContent[]
|
|
202
|
+
): Promise<JsonValue[]> {
|
|
203
|
+
return Promise.all(
|
|
204
|
+
contents.map(async (content): Promise<JsonValue> => {
|
|
205
|
+
const mimeType = bounded(stringValue(content.mimeType));
|
|
206
|
+
if ("text" in content && isString(content.text)) {
|
|
207
|
+
if (utf8ByteLength(content.text) <= MAX_INLINE_RESOURCE_TEXT_BYTES) {
|
|
208
|
+
return {
|
|
209
|
+
type: "text",
|
|
210
|
+
uri: bounded(content.uri),
|
|
211
|
+
text: content.text,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
type: "text",
|
|
216
|
+
uri: bounded(content.uri),
|
|
217
|
+
text: await artifactText(content.text, mimeType),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if ("blob" in content && isString(content.blob)) {
|
|
221
|
+
if (mimeType.startsWith("image/")) {
|
|
222
|
+
const estimatedBytes = Math.floor((content.blob.length * 3) / 4);
|
|
223
|
+
if (estimatedBytes <= MAX_INLINE_IMAGE_BYTES) {
|
|
224
|
+
return {
|
|
225
|
+
type: "image",
|
|
226
|
+
uri: bounded(content.uri),
|
|
227
|
+
data: content.blob,
|
|
228
|
+
mimeType,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
type: "binary-artifact",
|
|
234
|
+
uri: bounded(content.uri),
|
|
235
|
+
mimeType,
|
|
236
|
+
text: await artifactBinary(content.blob, mimeType),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
type: "text",
|
|
241
|
+
uri: bounded(content.uri),
|
|
242
|
+
text: "[MCP server returned an unsupported resource content type]",
|
|
243
|
+
};
|
|
244
|
+
})
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
const stringValue = (value: unknown): string =>
|
|
248
|
+
isString(value) ? value : "unknown";
|
|
249
|
+
const HIGH_SURROGATE_START = 0xd8_00;
|
|
250
|
+
const HIGH_SURROGATE_END = 0xdb_ff;
|
|
251
|
+
const LOW_SURROGATE_START = 0xdc_00;
|
|
252
|
+
const LOW_SURROGATE_END = 0xdf_ff;
|
|
253
|
+
const prefix = (value: string, length: number): string => {
|
|
254
|
+
const end = Math.min(value.length, length);
|
|
255
|
+
const chunks: string[] = [];
|
|
256
|
+
let index = 0;
|
|
257
|
+
while (index < end) {
|
|
258
|
+
const codeUnit = value.charCodeAt(index);
|
|
259
|
+
if (codeUnit >= HIGH_SURROGATE_START && codeUnit <= HIGH_SURROGATE_END) {
|
|
260
|
+
const nextCodeUnit = value.charCodeAt(index + 1);
|
|
261
|
+
const hasLowSurrogate =
|
|
262
|
+
index + 1 < value.length &&
|
|
263
|
+
nextCodeUnit >= LOW_SURROGATE_START &&
|
|
264
|
+
nextCodeUnit <= LOW_SURROGATE_END;
|
|
265
|
+
if (hasLowSurrogate && index + 1 >= end) {
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
if (hasLowSurrogate) {
|
|
269
|
+
chunks.push(value.slice(index, index + 2));
|
|
270
|
+
index += 2;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
chunks.push("\uFFFD");
|
|
274
|
+
} else if (
|
|
275
|
+
codeUnit >= LOW_SURROGATE_START &&
|
|
276
|
+
codeUnit <= LOW_SURROGATE_END
|
|
277
|
+
) {
|
|
278
|
+
chunks.push("\uFFFD");
|
|
279
|
+
} else {
|
|
280
|
+
chunks.push(value.charAt(index));
|
|
281
|
+
}
|
|
282
|
+
index += 1;
|
|
283
|
+
}
|
|
284
|
+
return chunks.join("");
|
|
285
|
+
};
|
|
286
|
+
const suffix = (value: string, length: number): string => {
|
|
287
|
+
let start = Math.max(0, value.length - length);
|
|
288
|
+
if (
|
|
289
|
+
start > 0 &&
|
|
290
|
+
value.charCodeAt(start) >= LOW_SURROGATE_START &&
|
|
291
|
+
value.charCodeAt(start) <= LOW_SURROGATE_END &&
|
|
292
|
+
value.charCodeAt(start - 1) >= HIGH_SURROGATE_START &&
|
|
293
|
+
value.charCodeAt(start - 1) <= HIGH_SURROGATE_END
|
|
294
|
+
) {
|
|
295
|
+
start += 1;
|
|
296
|
+
}
|
|
297
|
+
return prefix(value.slice(start), value.length - start);
|
|
298
|
+
};
|
|
299
|
+
const middleExcerpt = (value: string, keep: number): string => {
|
|
300
|
+
if (keep >= value.length) {
|
|
301
|
+
return prefix(value, keep);
|
|
302
|
+
}
|
|
303
|
+
const marker = "\n[… middle omitted …]\n";
|
|
304
|
+
if (keep <= marker.length) {
|
|
305
|
+
return prefix(value, keep);
|
|
306
|
+
}
|
|
307
|
+
const contentLength = keep - marker.length;
|
|
308
|
+
const headLength = Math.ceil(contentLength / 2);
|
|
309
|
+
const tailLength = contentLength - headLength;
|
|
310
|
+
return `${prefix(value, headLength)}${marker}${suffix(value, tailLength)}`;
|
|
311
|
+
};
|
|
312
|
+
const bounded = (value: string, max = 2048): string => {
|
|
313
|
+
const end = Math.min(value.length, max);
|
|
314
|
+
const chunks: string[] = [];
|
|
315
|
+
let index = 0;
|
|
316
|
+
while (index < end) {
|
|
317
|
+
const codeUnit = value.charCodeAt(index);
|
|
318
|
+
if (codeUnit >= 55_296 && codeUnit <= 56_319) {
|
|
319
|
+
if (
|
|
320
|
+
index + 1 < end &&
|
|
321
|
+
value.charCodeAt(index + 1) >= 56_320 &&
|
|
322
|
+
value.charCodeAt(index + 1) <= 57_343
|
|
323
|
+
) {
|
|
324
|
+
chunks.push(value.slice(index, index + 2));
|
|
325
|
+
index += 2;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
chunks.push("\uFFFD");
|
|
329
|
+
} else if (codeUnit >= 56_320 && codeUnit <= 57_343) {
|
|
330
|
+
chunks.push("\uFFFD");
|
|
331
|
+
} else {
|
|
332
|
+
chunks.push(value[index] ?? "");
|
|
333
|
+
}
|
|
334
|
+
index += 1;
|
|
335
|
+
}
|
|
336
|
+
return chunks.join("");
|
|
337
|
+
};
|
|
338
|
+
function safeJson(
|
|
339
|
+
value: unknown,
|
|
340
|
+
ancestors = new WeakSet<object>(),
|
|
341
|
+
depth = 0
|
|
342
|
+
): JsonValue | undefined {
|
|
343
|
+
if (isNull(value) || isString(value) || isBoolean(value)) {
|
|
344
|
+
return value;
|
|
345
|
+
}
|
|
346
|
+
if (isNumber(value)) {
|
|
347
|
+
return Number.isFinite(value) ? value : null;
|
|
348
|
+
}
|
|
349
|
+
if (typeof value !== "object" || depth > 32 || ancestors.has(value)) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
ancestors.add(value);
|
|
353
|
+
let result: JsonValue | undefined;
|
|
354
|
+
if (isArray(value)) {
|
|
355
|
+
result = value.flatMap((item) => {
|
|
356
|
+
const safe = safeJson(item, ancestors, depth + 1);
|
|
357
|
+
return isUndefined(safe) ? [] : [safe];
|
|
358
|
+
});
|
|
359
|
+
} else {
|
|
360
|
+
result = Object.fromEntries(
|
|
361
|
+
Object.entries(value).flatMap(([key, item]) => {
|
|
362
|
+
const safe = safeJson(item, ancestors, depth + 1);
|
|
363
|
+
return isUndefined(safe) ? [] : [[bounded(key), safe]];
|
|
364
|
+
})
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
ancestors.delete(value);
|
|
368
|
+
return result;
|
|
369
|
+
}
|
|
370
|
+
function normalizeContent(value: unknown): JsonValue[] {
|
|
371
|
+
if (!isArray(value)) {
|
|
372
|
+
return [];
|
|
373
|
+
}
|
|
374
|
+
return value.flatMap((item): JsonValue[] => {
|
|
375
|
+
if (!isPlainObject(item)) {
|
|
376
|
+
return [];
|
|
377
|
+
}
|
|
378
|
+
if (item.type === "text" && isString(item.text)) {
|
|
379
|
+
return [{ type: "text", text: item.text }];
|
|
380
|
+
}
|
|
381
|
+
if (item.type === "image" && isString(item.data)) {
|
|
382
|
+
return [
|
|
383
|
+
{
|
|
384
|
+
type: "image",
|
|
385
|
+
data: item.data,
|
|
386
|
+
mimeType: stringValue(item.mimeType),
|
|
387
|
+
},
|
|
388
|
+
];
|
|
389
|
+
}
|
|
390
|
+
if (item.type === "image" || item.type === "audio") {
|
|
391
|
+
return [
|
|
392
|
+
{
|
|
393
|
+
type: "binary-metadata",
|
|
394
|
+
mediaType: stringValue(item.mimeType),
|
|
395
|
+
originalType: item.type,
|
|
396
|
+
},
|
|
397
|
+
];
|
|
398
|
+
}
|
|
399
|
+
if (item.type === "resource" && isPlainObject(item.resource)) {
|
|
400
|
+
const resource = item.resource;
|
|
401
|
+
if (isString(resource.text)) {
|
|
402
|
+
return [
|
|
403
|
+
{
|
|
404
|
+
type: "resource",
|
|
405
|
+
uri: bounded(stringValue(resource.uri)),
|
|
406
|
+
text: resource.text,
|
|
407
|
+
mediaType: stringValue(resource.mimeType),
|
|
408
|
+
},
|
|
409
|
+
];
|
|
410
|
+
}
|
|
411
|
+
return [
|
|
412
|
+
{
|
|
413
|
+
type: "binary-metadata",
|
|
414
|
+
mediaType: stringValue(resource.mimeType),
|
|
415
|
+
originalType: "resource",
|
|
416
|
+
},
|
|
417
|
+
];
|
|
418
|
+
}
|
|
419
|
+
if (item.type === "resource_link") {
|
|
420
|
+
return [
|
|
421
|
+
{
|
|
422
|
+
type: "resource_link",
|
|
423
|
+
uri: bounded(stringValue(item.uri)),
|
|
424
|
+
name: bounded(stringValue(item.name)),
|
|
425
|
+
description: bounded(stringValue(item.description)),
|
|
426
|
+
},
|
|
427
|
+
];
|
|
428
|
+
}
|
|
429
|
+
return [];
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: bounded normalization handles protocol variants and cap fallback in one pass
|
|
433
|
+
export function normalizeMcpResult(input: unknown): McpNormalizedResult {
|
|
434
|
+
const cap = MAX_MCP_RESULT_BYTES;
|
|
435
|
+
const source = isPlainObject(input) ? input : {};
|
|
436
|
+
const result: McpNormalizedResult = {
|
|
437
|
+
content: normalizeContent(source.content),
|
|
438
|
+
isError: source.isError === true,
|
|
439
|
+
truncated: false,
|
|
440
|
+
};
|
|
441
|
+
const structured = safeJson(source.structuredContent);
|
|
442
|
+
if (!isUndefined(structured)) {
|
|
443
|
+
result.structuredContent = structured;
|
|
444
|
+
}
|
|
445
|
+
if (size(result) <= cap) {
|
|
446
|
+
return result;
|
|
447
|
+
}
|
|
448
|
+
result.truncated = true;
|
|
449
|
+
const marker = { type: "text", text: "[MCP output truncated]" } as JsonValue;
|
|
450
|
+
const texts = result.content.filter(
|
|
451
|
+
(item): item is { text: string } =>
|
|
452
|
+
isPlainObject(item) && isString(item.text)
|
|
453
|
+
);
|
|
454
|
+
const originals = texts.map((text) => text.text);
|
|
455
|
+
const lengths = texts.map((text) => text.text.length);
|
|
456
|
+
for (const text of texts) {
|
|
457
|
+
text.text = "";
|
|
458
|
+
}
|
|
459
|
+
result.content = [...result.content, marker];
|
|
460
|
+
if (size(result) > cap) {
|
|
461
|
+
result.structuredContent = undefined;
|
|
462
|
+
}
|
|
463
|
+
if (size(result) > cap) {
|
|
464
|
+
result.content = [marker];
|
|
465
|
+
}
|
|
466
|
+
if (size(result) > cap) {
|
|
467
|
+
return { content: [], isError: result.isError, truncated: true };
|
|
468
|
+
}
|
|
469
|
+
let low = 0;
|
|
470
|
+
let high = lengths.reduce((sum, length) => sum + length, 0);
|
|
471
|
+
while (low < high) {
|
|
472
|
+
const mid = Math.ceil((low + high) / 2);
|
|
473
|
+
let left = mid;
|
|
474
|
+
for (let index = 0; index < texts.length; index += 1) {
|
|
475
|
+
const text = texts[index];
|
|
476
|
+
if (!text) {
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
text.text = middleExcerpt(
|
|
480
|
+
originals[index] ?? "",
|
|
481
|
+
Math.min(left, lengths[index] ?? 0)
|
|
482
|
+
);
|
|
483
|
+
left = Math.max(0, left - (lengths[index] ?? 0));
|
|
484
|
+
}
|
|
485
|
+
if (size(result) <= cap) {
|
|
486
|
+
low = mid;
|
|
487
|
+
} else {
|
|
488
|
+
high = mid - 1;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
let left = low;
|
|
492
|
+
for (let index = 0; index < texts.length; index += 1) {
|
|
493
|
+
const text = texts[index];
|
|
494
|
+
if (!text) {
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
text.text = middleExcerpt(
|
|
498
|
+
originals[index] ?? "",
|
|
499
|
+
Math.min(left, lengths[index] ?? 0)
|
|
500
|
+
);
|
|
501
|
+
left = Math.max(0, left - (lengths[index] ?? 0));
|
|
502
|
+
}
|
|
503
|
+
return result;
|
|
504
|
+
}
|
package/src/sanitize.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getErrorMessage, isUndefined, sanitizeText } from "@wincode/utils";
|
|
2
|
+
import type { ResolvedMcpServerConfig } from "./config";
|
|
3
|
+
|
|
4
|
+
const MAX_SANITIZED_MESSAGE_LENGTH = 2048;
|
|
5
|
+
|
|
6
|
+
export const collectSecrets = (
|
|
7
|
+
config: ResolvedMcpServerConfig
|
|
8
|
+
): readonly string[] => {
|
|
9
|
+
if (config.type === "remote") {
|
|
10
|
+
return [...Object.values(config.headers ?? {}), config.url];
|
|
11
|
+
}
|
|
12
|
+
return [
|
|
13
|
+
...config.command.slice(1),
|
|
14
|
+
...Object.values(config.environment ?? {}),
|
|
15
|
+
];
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const sanitizeMessage = (
|
|
19
|
+
config: ResolvedMcpServerConfig | undefined,
|
|
20
|
+
error: unknown,
|
|
21
|
+
fallback: string
|
|
22
|
+
): string => {
|
|
23
|
+
const message = getErrorMessage(error, fallback);
|
|
24
|
+
if (isUndefined(config)) {
|
|
25
|
+
return fallback;
|
|
26
|
+
}
|
|
27
|
+
return sanitizeText(message, {
|
|
28
|
+
maxChars: MAX_SANITIZED_MESSAGE_LENGTH,
|
|
29
|
+
redactUrls: true,
|
|
30
|
+
secrets: collectSecrets(config),
|
|
31
|
+
});
|
|
32
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const MAX_NAME_LENGTH = 64;
|
|
2
|
+
const sanitize = (value: string): string =>
|
|
3
|
+
value.normalize("NFKD").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
4
|
+
|
|
5
|
+
/** Creates a bounded, collision-resistant MCP Tool dispatch name. */
|
|
6
|
+
export async function qualifyMcpToolName(
|
|
7
|
+
server: string,
|
|
8
|
+
tool: string
|
|
9
|
+
): Promise<string> {
|
|
10
|
+
const bytes = new TextEncoder().encode(JSON.stringify([server, tool]));
|
|
11
|
+
const digest = Array.from(
|
|
12
|
+
new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))
|
|
13
|
+
)
|
|
14
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
15
|
+
.join("")
|
|
16
|
+
.slice(0, 8);
|
|
17
|
+
const serverPart = sanitize(server);
|
|
18
|
+
const toolPart = sanitize(tool);
|
|
19
|
+
const available =
|
|
20
|
+
MAX_NAME_LENGTH - "mcp_".length - 2 - "_".length - digest.length;
|
|
21
|
+
const serverLength = Math.min(serverPart.length, Math.ceil(available / 2));
|
|
22
|
+
const toolLength = Math.min(toolPart.length, available - serverLength);
|
|
23
|
+
return `mcp_${serverPart.slice(0, serverLength)}_${toolPart.slice(0, toolLength)}_${digest}`;
|
|
24
|
+
}
|