@draht/mcp 2026.10.31 → 2026.11.5

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.
Files changed (79) hide show
  1. package/dist/config.d.ts +126 -0
  2. package/dist/config.d.ts.map +1 -0
  3. package/dist/config.js +167 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/index.d.ts +5 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/input-schema.d.ts +7 -0
  10. package/dist/input-schema.d.ts.map +1 -0
  11. package/dist/input-schema.js +13 -0
  12. package/dist/input-schema.js.map +1 -0
  13. package/dist/naming.d.ts +18 -0
  14. package/dist/naming.d.ts.map +1 -0
  15. package/dist/naming.js +29 -0
  16. package/dist/naming.js.map +1 -0
  17. package/dist/oauth/auth-provider.d.ts +63 -0
  18. package/dist/oauth/auth-provider.d.ts.map +1 -0
  19. package/dist/oauth/auth-provider.js +116 -0
  20. package/dist/oauth/auth-provider.js.map +1 -0
  21. package/dist/oauth/callback.d.ts.map +1 -1
  22. package/dist/oauth/callback.js +4 -0
  23. package/dist/oauth/callback.js.map +1 -1
  24. package/dist/oauth/client-metadata-base.d.ts +16 -0
  25. package/dist/oauth/client-metadata-base.d.ts.map +1 -0
  26. package/dist/oauth/client-metadata-base.js +27 -0
  27. package/dist/oauth/client-metadata-base.js.map +1 -0
  28. package/dist/oauth/client-settings.d.ts +131 -0
  29. package/dist/oauth/client-settings.d.ts.map +1 -0
  30. package/dist/oauth/client-settings.js +158 -0
  31. package/dist/oauth/client-settings.js.map +1 -0
  32. package/dist/oauth/errors.d.ts +7 -0
  33. package/dist/oauth/errors.d.ts.map +1 -1
  34. package/dist/oauth/errors.js +10 -0
  35. package/dist/oauth/errors.js.map +1 -1
  36. package/dist/oauth/flow.d.ts +33 -0
  37. package/dist/oauth/flow.d.ts.map +1 -1
  38. package/dist/oauth/flow.js +64 -10
  39. package/dist/oauth/flow.js.map +1 -1
  40. package/dist/oauth/index.d.ts +7 -2
  41. package/dist/oauth/index.d.ts.map +1 -1
  42. package/dist/oauth/index.js +6 -1
  43. package/dist/oauth/index.js.map +1 -1
  44. package/dist/oauth/loopback.d.ts +55 -0
  45. package/dist/oauth/loopback.d.ts.map +1 -0
  46. package/dist/oauth/loopback.js +106 -0
  47. package/dist/oauth/loopback.js.map +1 -0
  48. package/dist/oauth/provider.d.ts +4 -1
  49. package/dist/oauth/provider.d.ts.map +1 -1
  50. package/dist/oauth/provider.js +9 -3
  51. package/dist/oauth/provider.js.map +1 -1
  52. package/dist/oauth/sign-in.d.ts +82 -0
  53. package/dist/oauth/sign-in.d.ts.map +1 -0
  54. package/dist/oauth/sign-in.js +209 -0
  55. package/dist/oauth/sign-in.js.map +1 -0
  56. package/dist/oauth/types.d.ts +1 -0
  57. package/dist/oauth/types.d.ts.map +1 -1
  58. package/dist/oauth/types.js +8 -4
  59. package/dist/oauth/types.js.map +1 -1
  60. package/dist/output-limit.d.ts +24 -0
  61. package/dist/output-limit.d.ts.map +1 -0
  62. package/dist/output-limit.js +58 -0
  63. package/dist/output-limit.js.map +1 -0
  64. package/dist/transports/lines.d.ts +34 -0
  65. package/dist/transports/lines.d.ts.map +1 -0
  66. package/dist/transports/lines.js +85 -0
  67. package/dist/transports/lines.js.map +1 -0
  68. package/dist/transports/pipe.d.ts +49 -0
  69. package/dist/transports/pipe.d.ts.map +1 -0
  70. package/dist/transports/pipe.js +96 -0
  71. package/dist/transports/pipe.js.map +1 -0
  72. package/dist/transports/stdio.d.ts +1 -4
  73. package/dist/transports/stdio.d.ts.map +1 -1
  74. package/dist/transports/stdio.js +20 -51
  75. package/dist/transports/stdio.js.map +1 -1
  76. package/dist/transports/streamable-http.d.ts.map +1 -1
  77. package/dist/transports/streamable-http.js +77 -11
  78. package/dist/transports/streamable-http.js.map +1 -1
  79. package/package.json +3 -4
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../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B,CAAC;IAClD,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,eAAe;IAC/B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,2BAA2B,CAAC,EAAE,2BAA2B,CAAC;IAC1D,gBAAgB,CAAC,EAAE,8BAA8B,CAAC;CAClD;AAED,MAAM,WAAW,cAAc;IAC9B,mBAAmB,CAAC,EAAE,GAAG,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AA4CD,wBAAgB,SAAS,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAE3C;AAMD,wBAAgB,8BAA8B,CAAC,KAAK,EAAE,OAAO,GAAG,8BAA8B,CAU7F;AAED,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,OAAO,GAAG,2BAA2B,CA8B5F;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,CAa5D;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,CAWjF"}
@@ -34,16 +34,20 @@ function optionalStrings(value, name) {
34
34
  throw new Error(`Invalid ${name}`);
35
35
  return [...value];
36
36
  }
37
+ /**
38
+ * Accepts only `http:` and `https:` URLs. Servers supply these URLs, and the authorization endpoint is
39
+ * opened with the platform URL handler, so a `file:` or custom protocol URL would launch local programs.
40
+ */
37
41
  function safeUrl(value, name) {
38
42
  const text = requiredString(value, name);
39
43
  // URL parsing throws a `TypeError`, which discovery reserves for network failures.
40
- if (!URL.canParse(text))
41
- throw new Error(`Invalid ${name}`);
42
- const url = new URL(text);
43
- if (["javascript:", "data:", "vbscript:"].includes(url.protocol))
44
+ if (!URL.canParse(text) || !isHttpUrl(new URL(text)))
44
45
  throw new Error(`Invalid ${name}`);
45
46
  return text;
46
47
  }
48
+ export function isHttpUrl(url) {
49
+ return url.protocol === "http:" || url.protocol === "https:";
50
+ }
47
51
  function optionalUrl(value, name) {
48
52
  return absent(value) ? undefined : safeUrl(value, name);
49
53
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/oauth/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAwFlD,SAAS,MAAM,CAAC,KAAc,EAAE,IAAY;IAC3C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IACzD,OAAO,KAAK,CAAC;AACd,CAAC;AAED,gGAAgG;AAChG,SAAS,OAAO,CAAmB,KAAQ;IAC1C,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAM,CAAC;AAChG,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,IAAY;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IACxF,OAAO,KAAK,CAAC;AACd,CAAC;AAED,+GAA+G;AAC/G,SAAS,MAAM,CAAC,KAAc;IAC7B,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;AAC9D,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,IAAY;IACnD,IAAI,MAAM,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACpC,OAAO,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,IAAY;IACpD,IAAI,KAAK,KAAK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,EAAE,cAAc,CAAC,KAAK,CAAC,aAAa,EAAE,eAAe,CAAC;QACnE,mBAAmB,EAAE,OAAO,KAAK,CAAC,mBAAmB,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS;QAC1G,wBAAwB,EACvB,OAAO,KAAK,CAAC,wBAAwB,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC,SAAS;QAChG,aAAa,EAAE,eAAe,CAAC,KAAK,CAAC,aAAa,EAAE,eAAe,CAAC,IAAI,EAAE;KAC1E,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.\n * Modified to use dependency-free structural validation.\n */\n\nimport { isObject } from \"../protocol/jsonrpc.ts\";\n\nexport interface OAuthProtectedResourceMetadata {\n\tresource: string;\n\tauthorization_servers?: string[];\n\tscopes_supported?: string[];\n\t[key: string]: unknown;\n}\n\nexport interface AuthorizationServerMetadata {\n\tissuer: string;\n\tauthorization_endpoint: string;\n\ttoken_endpoint: string;\n\tregistration_endpoint?: string;\n\tscopes_supported?: string[];\n\tresponse_types_supported: string[];\n\tgrant_types_supported?: string[];\n\ttoken_endpoint_auth_methods_supported?: string[];\n\tcode_challenge_methods_supported?: string[];\n\tclient_id_metadata_document_supported?: boolean;\n\t/** Whether authorization responses carry an `iss` parameter (RFC 9207). */\n\tauthorization_response_iss_parameter_supported?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface OAuthTokens {\n\taccess_token: string;\n\ttoken_type: string;\n\texpires_in?: number;\n\tscope?: string;\n\trefresh_token?: string;\n\tid_token?: string;\n}\n\nexport interface OAuthClientMetadata {\n\tredirect_uris: string[];\n\ttoken_endpoint_auth_method?: string;\n\tgrant_types?: string[];\n\tresponse_types?: string[];\n\t/**\n\t * OpenID Connect client type, `native` or `web`. Dynamic client registration derives it from\n\t * `redirect_uris` when absent (MCP SEP-837).\n\t */\n\tapplication_type?: string;\n\tclient_name?: string;\n\tclient_uri?: string;\n\tlogo_uri?: string;\n\tscope?: string;\n\tcontacts?: string[];\n\ttos_uri?: string;\n\tpolicy_uri?: string;\n\tjwks_uri?: string;\n\tjwks?: unknown;\n\tsoftware_id?: string;\n\tsoftware_version?: string;\n\tsoftware_statement?: string;\n}\n\nexport interface OAuthClientInformation {\n\tclient_id: string;\n\tclient_secret?: string;\n\tclient_id_issued_at?: number;\n\tclient_secret_expires_at?: number;\n}\n\nexport type OAuthClientInformationFull = OAuthClientInformation & OAuthClientMetadata;\nexport type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;\n\nexport interface OAuthDiscoveryState {\n\tauthorizationServerUrl: string;\n\tauthorizationServerMetadata?: AuthorizationServerMetadata;\n\tresourceMetadata?: OAuthProtectedResourceMetadata;\n\tresourceMetadataUrl?: string;\n}\n\nexport interface OAuthServerInfo {\n\tauthorizationServerUrl: string;\n\tauthorizationServerMetadata?: AuthorizationServerMetadata;\n\tresourceMetadata?: OAuthProtectedResourceMetadata;\n}\n\nexport interface OAuthChallenge {\n\tresourceMetadataUrl?: URL;\n\tscope?: string;\n\terror?: string;\n\terrorDescription?: string;\n}\n\nfunction object(value: unknown, name: string): Record<string, unknown> {\n\tif (!isObject(value)) throw new Error(`Invalid ${name}`);\n\treturn value;\n}\n\n/** Drops `undefined` values so optional fields are absent rather than present-but-undefined. */\nfunction compact<T extends object>(value: T): T {\n\treturn Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;\n}\n\nfunction requiredString(value: unknown, name: string): string {\n\tif (typeof value !== \"string\" || value.length === 0) throw new Error(`Invalid ${name}`);\n\treturn value;\n}\n\n/** Treats `null` and `\"\"` as absent: servers send them for fields they have no value for, like `scope: \"\"`. */\nfunction absent(value: unknown): value is undefined | null | \"\" {\n\treturn value === undefined || value === null || value === \"\";\n}\n\nfunction optionalString(value: unknown, name: string): string | undefined {\n\tif (absent(value)) return undefined;\n\treturn requiredString(value, name);\n}\n\nfunction optionalStrings(value: unknown, name: string): string[] | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new Error(`Invalid ${name}`);\n\treturn [...value];\n}\n\nfunction safeUrl(value: unknown, name: string): string {\n\tconst text = requiredString(value, name);\n\t// URL parsing throws a `TypeError`, which discovery reserves for network failures.\n\tif (!URL.canParse(text)) throw new Error(`Invalid ${name}`);\n\tconst url = new URL(text);\n\tif ([\"javascript:\", \"data:\", \"vbscript:\"].includes(url.protocol)) throw new Error(`Invalid ${name}`);\n\treturn text;\n}\n\nfunction optionalUrl(value: unknown, name: string): string | undefined {\n\treturn absent(value) ? undefined : safeUrl(value, name);\n}\n\nexport function parseProtectedResourceMetadata(value: unknown): OAuthProtectedResourceMetadata {\n\tconst input = object(value, \"OAuth protected resource metadata\");\n\treturn compact({\n\t\t...input,\n\t\tresource: safeUrl(input.resource, \"OAuth protected resource metadata resource\"),\n\t\tauthorization_servers: optionalStrings(input.authorization_servers, \"authorization_servers\")?.map((url) =>\n\t\t\tsafeUrl(url, \"authorization server URL\"),\n\t\t),\n\t\tscopes_supported: optionalStrings(input.scopes_supported, \"scopes_supported\"),\n\t});\n}\n\nexport function parseAuthorizationServerMetadata(value: unknown): AuthorizationServerMetadata {\n\tconst input = object(value, \"authorization server metadata\");\n\tconst responseTypes = optionalStrings(input.response_types_supported, \"response_types_supported\");\n\tif (!responseTypes) throw new Error(\"Invalid response_types_supported\");\n\treturn compact({\n\t\t...input,\n\t\tissuer: safeUrl(input.issuer, \"authorization server issuer\"),\n\t\tauthorization_endpoint: safeUrl(input.authorization_endpoint, \"authorization endpoint\"),\n\t\ttoken_endpoint: safeUrl(input.token_endpoint, \"token endpoint\"),\n\t\tregistration_endpoint: optionalUrl(input.registration_endpoint, \"registration endpoint\"),\n\t\tscopes_supported: optionalStrings(input.scopes_supported, \"scopes_supported\"),\n\t\tresponse_types_supported: responseTypes,\n\t\tgrant_types_supported: optionalStrings(input.grant_types_supported, \"grant_types_supported\"),\n\t\ttoken_endpoint_auth_methods_supported: optionalStrings(\n\t\t\tinput.token_endpoint_auth_methods_supported,\n\t\t\t\"token_endpoint_auth_methods_supported\",\n\t\t),\n\t\tcode_challenge_methods_supported: optionalStrings(\n\t\t\tinput.code_challenge_methods_supported,\n\t\t\t\"code_challenge_methods_supported\",\n\t\t),\n\t\tclient_id_metadata_document_supported:\n\t\t\ttypeof input.client_id_metadata_document_supported === \"boolean\"\n\t\t\t\t? input.client_id_metadata_document_supported\n\t\t\t\t: undefined,\n\t\tauthorization_response_iss_parameter_supported:\n\t\t\ttypeof input.authorization_response_iss_parameter_supported === \"boolean\"\n\t\t\t\t? input.authorization_response_iss_parameter_supported\n\t\t\t\t: undefined,\n\t});\n}\n\nexport function parseOAuthTokens(value: unknown): OAuthTokens {\n\tconst input = object(value, \"OAuth token response\");\n\t// `Number(null)` is 0, which would mark the token as expired at once.\n\tconst expires = absent(input.expires_in) ? undefined : Number(input.expires_in);\n\tif (expires !== undefined && !Number.isFinite(expires)) throw new Error(\"Invalid expires_in\");\n\treturn compact({\n\t\taccess_token: requiredString(input.access_token, \"access_token\"),\n\t\ttoken_type: requiredString(input.token_type, \"token_type\"),\n\t\texpires_in: expires,\n\t\tscope: optionalString(input.scope, \"scope\"),\n\t\trefresh_token: optionalString(input.refresh_token, \"refresh_token\"),\n\t\tid_token: optionalString(input.id_token, \"id_token\"),\n\t});\n}\n\nexport function parseClientInformation(value: unknown): OAuthClientInformationFull {\n\tconst input = object(value, \"OAuth client registration response\");\n\treturn compact({\n\t\t...(input as unknown as OAuthClientMetadata),\n\t\tclient_id: requiredString(input.client_id, \"client_id\"),\n\t\tclient_secret: optionalString(input.client_secret, \"client_secret\"),\n\t\tclient_id_issued_at: typeof input.client_id_issued_at === \"number\" ? input.client_id_issued_at : undefined,\n\t\tclient_secret_expires_at:\n\t\t\ttypeof input.client_secret_expires_at === \"number\" ? input.client_secret_expires_at : undefined,\n\t\tredirect_uris: optionalStrings(input.redirect_uris, \"redirect_uris\") ?? [],\n\t});\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/oauth/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAwFlD,SAAS,MAAM,CAAC,KAAc,EAAE,IAAY;IAC3C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IACzD,OAAO,KAAK,CAAC;AACd,CAAC;AAED,gGAAgG;AAChG,SAAS,OAAO,CAAmB,KAAQ;IAC1C,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAM,CAAC;AAChG,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,IAAY;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IACxF,OAAO,KAAK,CAAC;AACd,CAAC;AAED,+GAA+G;AAC/G,SAAS,MAAM,CAAC,KAAc;IAC7B,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;AAC9D,CAAC;AAED,SAAS,cAAc,CAAC,KAAc,EAAE,IAAY;IACnD,IAAI,MAAM,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACpC,OAAO,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,IA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AAC;QACvD,aAAa,EAAE,cAAc,CAAC,KAAK,CAAC,aAAa,EAAE,eAAe,CAAC;QACnE,mBAAmB,EAAE,OAAO,KAAK,CAAC,mBAAmB,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS;QAC1G,wBAAwB,EACvB,OAAO,KAAK,CAAC,wBAAwB,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC,SAAS;QAChG,aAAa,EAAE,eAAe,CAAC,KAAK,CAAC,aAAa,EAAE,eAAe,CAAC,IAAI,EAAE;KAC1E,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.\n * Modified to use dependency-free structural validation.\n */\n\nimport { isObject } from \"../protocol/jsonrpc.ts\";\n\nexport interface OAuthProtectedResourceMetadata {\n\tresource: string;\n\tauthorization_servers?: string[];\n\tscopes_supported?: string[];\n\t[key: string]: unknown;\n}\n\nexport interface AuthorizationServerMetadata {\n\tissuer: string;\n\tauthorization_endpoint: string;\n\ttoken_endpoint: string;\n\tregistration_endpoint?: string;\n\tscopes_supported?: string[];\n\tresponse_types_supported: string[];\n\tgrant_types_supported?: string[];\n\ttoken_endpoint_auth_methods_supported?: string[];\n\tcode_challenge_methods_supported?: string[];\n\tclient_id_metadata_document_supported?: boolean;\n\t/** Whether authorization responses carry an `iss` parameter (RFC 9207). */\n\tauthorization_response_iss_parameter_supported?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface OAuthTokens {\n\taccess_token: string;\n\ttoken_type: string;\n\texpires_in?: number;\n\tscope?: string;\n\trefresh_token?: string;\n\tid_token?: string;\n}\n\nexport interface OAuthClientMetadata {\n\tredirect_uris: string[];\n\ttoken_endpoint_auth_method?: string;\n\tgrant_types?: string[];\n\tresponse_types?: string[];\n\t/**\n\t * OpenID Connect client type, `native` or `web`. Dynamic client registration derives it from\n\t * `redirect_uris` when absent (MCP SEP-837).\n\t */\n\tapplication_type?: string;\n\tclient_name?: string;\n\tclient_uri?: string;\n\tlogo_uri?: string;\n\tscope?: string;\n\tcontacts?: string[];\n\ttos_uri?: string;\n\tpolicy_uri?: string;\n\tjwks_uri?: string;\n\tjwks?: unknown;\n\tsoftware_id?: string;\n\tsoftware_version?: string;\n\tsoftware_statement?: string;\n}\n\nexport interface OAuthClientInformation {\n\tclient_id: string;\n\tclient_secret?: string;\n\tclient_id_issued_at?: number;\n\tclient_secret_expires_at?: number;\n}\n\nexport type OAuthClientInformationFull = OAuthClientInformation & OAuthClientMetadata;\nexport type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;\n\nexport interface OAuthDiscoveryState {\n\tauthorizationServerUrl: string;\n\tauthorizationServerMetadata?: AuthorizationServerMetadata;\n\tresourceMetadata?: OAuthProtectedResourceMetadata;\n\tresourceMetadataUrl?: string;\n}\n\nexport interface OAuthServerInfo {\n\tauthorizationServerUrl: string;\n\tauthorizationServerMetadata?: AuthorizationServerMetadata;\n\tresourceMetadata?: OAuthProtectedResourceMetadata;\n}\n\nexport interface OAuthChallenge {\n\tresourceMetadataUrl?: URL;\n\tscope?: string;\n\terror?: string;\n\terrorDescription?: string;\n}\n\nfunction object(value: unknown, name: string): Record<string, unknown> {\n\tif (!isObject(value)) throw new Error(`Invalid ${name}`);\n\treturn value;\n}\n\n/** Drops `undefined` values so optional fields are absent rather than present-but-undefined. */\nfunction compact<T extends object>(value: T): T {\n\treturn Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;\n}\n\nfunction requiredString(value: unknown, name: string): string {\n\tif (typeof value !== \"string\" || value.length === 0) throw new Error(`Invalid ${name}`);\n\treturn value;\n}\n\n/** Treats `null` and `\"\"` as absent: servers send them for fields they have no value for, like `scope: \"\"`. */\nfunction absent(value: unknown): value is undefined | null | \"\" {\n\treturn value === undefined || value === null || value === \"\";\n}\n\nfunction optionalString(value: unknown, name: string): string | undefined {\n\tif (absent(value)) return undefined;\n\treturn requiredString(value, name);\n}\n\nfunction optionalStrings(value: unknown, name: string): string[] | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new Error(`Invalid ${name}`);\n\treturn [...value];\n}\n\n/**\n * Accepts only `http:` and `https:` URLs. Servers supply these URLs, and the authorization endpoint is\n * opened with the platform URL handler, so a `file:` or custom protocol URL would launch local programs.\n */\nfunction safeUrl(value: unknown, name: string): string {\n\tconst text = requiredString(value, name);\n\t// URL parsing throws a `TypeError`, which discovery reserves for network failures.\n\tif (!URL.canParse(text) || !isHttpUrl(new URL(text))) throw new Error(`Invalid ${name}`);\n\treturn text;\n}\n\nexport function isHttpUrl(url: URL): boolean {\n\treturn url.protocol === \"http:\" || url.protocol === \"https:\";\n}\n\nfunction optionalUrl(value: unknown, name: string): string | undefined {\n\treturn absent(value) ? undefined : safeUrl(value, name);\n}\n\nexport function parseProtectedResourceMetadata(value: unknown): OAuthProtectedResourceMetadata {\n\tconst input = object(value, \"OAuth protected resource metadata\");\n\treturn compact({\n\t\t...input,\n\t\tresource: safeUrl(input.resource, \"OAuth protected resource metadata resource\"),\n\t\tauthorization_servers: optionalStrings(input.authorization_servers, \"authorization_servers\")?.map((url) =>\n\t\t\tsafeUrl(url, \"authorization server URL\"),\n\t\t),\n\t\tscopes_supported: optionalStrings(input.scopes_supported, \"scopes_supported\"),\n\t});\n}\n\nexport function parseAuthorizationServerMetadata(value: unknown): AuthorizationServerMetadata {\n\tconst input = object(value, \"authorization server metadata\");\n\tconst responseTypes = optionalStrings(input.response_types_supported, \"response_types_supported\");\n\tif (!responseTypes) throw new Error(\"Invalid response_types_supported\");\n\treturn compact({\n\t\t...input,\n\t\tissuer: safeUrl(input.issuer, \"authorization server issuer\"),\n\t\tauthorization_endpoint: safeUrl(input.authorization_endpoint, \"authorization endpoint\"),\n\t\ttoken_endpoint: safeUrl(input.token_endpoint, \"token endpoint\"),\n\t\tregistration_endpoint: optionalUrl(input.registration_endpoint, \"registration endpoint\"),\n\t\tscopes_supported: optionalStrings(input.scopes_supported, \"scopes_supported\"),\n\t\tresponse_types_supported: responseTypes,\n\t\tgrant_types_supported: optionalStrings(input.grant_types_supported, \"grant_types_supported\"),\n\t\ttoken_endpoint_auth_methods_supported: optionalStrings(\n\t\t\tinput.token_endpoint_auth_methods_supported,\n\t\t\t\"token_endpoint_auth_methods_supported\",\n\t\t),\n\t\tcode_challenge_methods_supported: optionalStrings(\n\t\t\tinput.code_challenge_methods_supported,\n\t\t\t\"code_challenge_methods_supported\",\n\t\t),\n\t\tclient_id_metadata_document_supported:\n\t\t\ttypeof input.client_id_metadata_document_supported === \"boolean\"\n\t\t\t\t? input.client_id_metadata_document_supported\n\t\t\t\t: undefined,\n\t\tauthorization_response_iss_parameter_supported:\n\t\t\ttypeof input.authorization_response_iss_parameter_supported === \"boolean\"\n\t\t\t\t? input.authorization_response_iss_parameter_supported\n\t\t\t\t: undefined,\n\t});\n}\n\nexport function parseOAuthTokens(value: unknown): OAuthTokens {\n\tconst input = object(value, \"OAuth token response\");\n\t// `Number(null)` is 0, which would mark the token as expired at once.\n\tconst expires = absent(input.expires_in) ? undefined : Number(input.expires_in);\n\tif (expires !== undefined && !Number.isFinite(expires)) throw new Error(\"Invalid expires_in\");\n\treturn compact({\n\t\taccess_token: requiredString(input.access_token, \"access_token\"),\n\t\ttoken_type: requiredString(input.token_type, \"token_type\"),\n\t\texpires_in: expires,\n\t\tscope: optionalString(input.scope, \"scope\"),\n\t\trefresh_token: optionalString(input.refresh_token, \"refresh_token\"),\n\t\tid_token: optionalString(input.id_token, \"id_token\"),\n\t});\n}\n\nexport function parseClientInformation(value: unknown): OAuthClientInformationFull {\n\tconst input = object(value, \"OAuth client registration response\");\n\treturn compact({\n\t\t...(input as unknown as OAuthClientMetadata),\n\t\tclient_id: requiredString(input.client_id, \"client_id\"),\n\t\tclient_secret: optionalString(input.client_secret, \"client_secret\"),\n\t\tclient_id_issued_at: typeof input.client_id_issued_at === \"number\" ? input.client_id_issued_at : undefined,\n\t\tclient_secret_expires_at:\n\t\t\ttypeof input.client_secret_expires_at === \"number\" ? input.client_secret_expires_at : undefined,\n\t\tredirect_uris: optionalStrings(input.redirect_uris, \"redirect_uris\") ?? [],\n\t});\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The size limit of the model-facing text of MCP results. Longer text keeps its start and end with the
3
+ * middle cut out, like Codex does, and the caller may save the full text where the model can read it.
4
+ */
5
+ import type { LlmContent } from "./protocol/content.ts";
6
+ /** Model-facing text of an MCP result beyond this is cut in the middle. */
7
+ export declare const MCP_OUTPUT_MAX_BYTES: number;
8
+ /**
9
+ * Saves data the model cannot get in full, such as the full text of a truncated result, and returns
10
+ * where it was saved (a path the model can read). `extension` includes the dot, for example `.txt`.
11
+ */
12
+ export type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;
13
+ /** Model-facing content within the limit, and where the full text went when it was saved. */
14
+ export interface LimitedMcpContent {
15
+ content: LlmContent[];
16
+ fullOutputPath?: string;
17
+ }
18
+ /**
19
+ * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in
20
+ * Codex's truncation format, followed by the path of the file with the full text when `saveOutput`
21
+ * is given; images follow it. Content within the limit is returned as it is.
22
+ */
23
+ export declare function limitMcpContent(content: LlmContent[], saveOutput?: McpOutputSaver): Promise<LimitedMcpContent>;
24
+ //# sourceMappingURL=output-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-limit.d.ts","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAExD,2EAA2E;AAC3E,eAAO,MAAM,oBAAoB,QAAY,CAAC;AAE9C;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;AAE/F,6FAA6F;AAC7F,MAAM,WAAW,iBAAiB;IACjC,OAAO,EAAE,UAAU,EAAE,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,UAAU,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAoBpH"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The size limit of the model-facing text of MCP results. Longer text keeps its start and end with the
3
+ * middle cut out, like Codex does, and the caller may save the full text where the model can read it.
4
+ */
5
+ /** Model-facing text of an MCP result beyond this is cut in the middle. */
6
+ export const MCP_OUTPUT_MAX_BYTES = 20 * 1024;
7
+ /**
8
+ * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in
9
+ * Codex's truncation format, followed by the path of the file with the full text when `saveOutput`
10
+ * is given; images follow it. Content within the limit is returned as it is.
11
+ */
12
+ export async function limitMcpContent(content, saveOutput) {
13
+ const combined = content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
14
+ const truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);
15
+ if (!truncation)
16
+ return { content };
17
+ let fullOutputPath;
18
+ let where = "";
19
+ if (saveOutput) {
20
+ try {
21
+ fullOutputPath = await saveOutput(combined, ".txt");
22
+ where = `\n\n[Full output: ${fullOutputPath} (read it with offset/limit)]`;
23
+ }
24
+ catch (error) {
25
+ where = `\n\n[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;
26
+ }
27
+ }
28
+ const tokens = Math.ceil(truncation.totalBytes / 4);
29
+ const text = `Warning: truncated output (original token count: ${tokens})\nTotal output lines: ${truncation.totalLines}\n\n${truncation.content}${where}`;
30
+ return {
31
+ content: [{ type: "text", text }, ...content.filter((block) => block.type === "image")],
32
+ ...(fullOutputPath ? { fullOutputPath } : {}),
33
+ };
34
+ }
35
+ /**
36
+ * Keep the start and the end of `text`, half of `maxBytes` each, and replace the middle with a
37
+ * `…N chars truncated…` marker. Cuts only at character boundaries. Undefined when `text` fits.
38
+ */
39
+ function truncateMiddle(text, maxBytes) {
40
+ const buf = Buffer.from(text, "utf-8");
41
+ if (buf.length <= maxBytes)
42
+ return undefined;
43
+ // Continuation bytes (10xxxxxx) are not character starts.
44
+ const isBoundary = (index) => index >= buf.length || (buf[index] & 0xc0) !== 0x80;
45
+ let headEnd = Math.floor(maxBytes / 2);
46
+ while (headEnd > 0 && !isBoundary(headEnd))
47
+ headEnd--;
48
+ let tailStart = buf.length - (maxBytes - Math.floor(maxBytes / 2));
49
+ while (tailStart < buf.length && !isBoundary(tailStart))
50
+ tailStart++;
51
+ const head = buf.subarray(0, headEnd).toString("utf-8");
52
+ const tail = buf.subarray(tailStart).toString("utf-8");
53
+ const removedChars = Array.from(buf.subarray(headEnd, tailStart).toString("utf-8")).length;
54
+ // A final newline ends the last line instead of starting another.
55
+ const lines = text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
56
+ return { content: `${head}…${removedChars} chars truncated…${tail}`, totalBytes: buf.length, totalLines: lines };
57
+ }
58
+ //# sourceMappingURL=output-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-limit.js","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAc9C;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,OAAqB,EAAE,UAA2B;IACvF,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IA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CAAC,CAAC;IACtE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,IAAI,YAAY,oBAAoB,IAAI,EAAE,EAAE,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AAClH,CAAC","sourcesContent":["/**\n * The size limit of the model-facing text of MCP results. Longer text keeps its start and end with the\n * middle cut out, like Codex does, and the caller may save the full text where the model can read it.\n */\n\nimport type { LlmContent } from \"./protocol/content.ts\";\n\n/** Model-facing text of an MCP result beyond this is cut in the middle. */\nexport const MCP_OUTPUT_MAX_BYTES = 20 * 1024;\n\n/**\n * Saves data the model cannot get in full, such as the full text of a truncated result, and returns\n * where it was saved (a path the model can read). `extension` includes the dot, for example `.txt`.\n */\nexport type McpOutputSaver = (data: string | Uint8Array, extension: string) => Promise<string>;\n\n/** Model-facing content within the limit, and where the full text went when it was saved. */\nexport interface LimitedMcpContent {\n\tcontent: LlmContent[];\n\tfullOutputPath?: string;\n}\n\n/**\n * Keep model-facing text within {@link MCP_OUTPUT_MAX_BYTES}. Longer text becomes one text block in\n * Codex's truncation format, followed by the path of the file with the full text when `saveOutput`\n * is given; images follow it. Content within the limit is returned as it is.\n */\nexport async function limitMcpContent(content: LlmContent[], saveOutput?: McpOutputSaver): Promise<LimitedMcpContent> {\n\tconst combined = content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n\tconst truncation = truncateMiddle(combined, MCP_OUTPUT_MAX_BYTES);\n\tif (!truncation) return { content };\n\tlet fullOutputPath: string | undefined;\n\tlet where = \"\";\n\tif (saveOutput) {\n\t\ttry {\n\t\t\tfullOutputPath = await saveOutput(combined, \".txt\");\n\t\t\twhere = `\\n\\n[Full output: ${fullOutputPath} (read it with offset/limit)]`;\n\t\t} catch (error) {\n\t\t\twhere = `\\n\\n[Could not save the full output: ${error instanceof Error ? error.message : String(error)}]`;\n\t\t}\n\t}\n\tconst tokens = Math.ceil(truncation.totalBytes / 4);\n\tconst text = `Warning: truncated output (original token count: ${tokens})\\nTotal output lines: ${truncation.totalLines}\\n\\n${truncation.content}${where}`;\n\treturn {\n\t\tcontent: [{ type: \"text\", text }, ...content.filter((block) => block.type === \"image\")],\n\t\t...(fullOutputPath ? { fullOutputPath } : {}),\n\t};\n}\n\n/** Text cut in the middle, with the size of the whole text. */\ninterface MiddleTruncation {\n\t/** The start and the end of the text with a `…N chars truncated…` marker between them. */\n\tcontent: string;\n\ttotalBytes: number;\n\ttotalLines: number;\n}\n\n/**\n * Keep the start and the end of `text`, half of `maxBytes` each, and replace the middle with a\n * `…N chars truncated…` marker. Cuts only at character boundaries. Undefined when `text` fits.\n */\nfunction truncateMiddle(text: string, maxBytes: number): MiddleTruncation | undefined {\n\tconst buf = Buffer.from(text, \"utf-8\");\n\tif (buf.length <= maxBytes) return undefined;\n\t// Continuation bytes (10xxxxxx) are not character starts.\n\tconst isBoundary = (index: number) => index >= buf.length || (buf[index] & 0xc0) !== 0x80;\n\tlet headEnd = Math.floor(maxBytes / 2);\n\twhile (headEnd > 0 && !isBoundary(headEnd)) headEnd--;\n\tlet tailStart = buf.length - (maxBytes - Math.floor(maxBytes / 2));\n\twhile (tailStart < buf.length && !isBoundary(tailStart)) tailStart++;\n\tconst head = buf.subarray(0, headEnd).toString(\"utf-8\");\n\tconst tail = buf.subarray(tailStart).toString(\"utf-8\");\n\tconst removedChars = Array.from(buf.subarray(headEnd, tailStart).toString(\"utf-8\")).length;\n\t// A final newline ends the last line instead of starting another.\n\tconst lines = text.split(\"\\n\").length - (text.endsWith(\"\\n\") ? 1 : 0);\n\treturn { content: `${head}…${removedChars} chars truncated…${tail}`, totalBytes: buf.length, totalLines: lines };\n}\n"]}
@@ -0,0 +1,34 @@
1
+ import { type JsonRpcMessage } from "../protocol/jsonrpc.ts";
2
+ export interface JsonRpcLineReaderOptions {
3
+ maxMessageBytes?: number;
4
+ maxStderrBytes?: number;
5
+ /** Every stderr chunk, decoded as UTF-8. */
6
+ onStderr?: (chunk: string) => void;
7
+ onMessage(message: JsonRpcMessage): void;
8
+ onError(error: unknown): void;
9
+ }
10
+ /**
11
+ * Reads a program's output as MCP's stdio framing: newline-delimited JSON-RPC messages on stdout, and a bounded
12
+ * tail of stderr for diagnostics.
13
+ */
14
+ export declare class JsonRpcLineReader {
15
+ private readonly options;
16
+ /** The bytes of the incomplete message received so far. */
17
+ private stdoutChunks;
18
+ private stdoutPendingBytes;
19
+ private stderrBuffer;
20
+ constructor(options: JsonRpcLineReaderOptions);
21
+ /** The last `maxStderrBytes` of stderr. */
22
+ get stderr(): string;
23
+ /**
24
+ * Takes the next stdout bytes and reports every complete message, or the error parsing it. Bytes of an
25
+ * incomplete message are kept as chunks and joined once when its newline arrives, so a large message that
26
+ * arrives in many chunks is copied and scanned only once.
27
+ */
28
+ readStdout(chunk: Uint8Array): void;
29
+ /** Takes the next stderr bytes into the tail and passes them to `onStderr`. */
30
+ readStderr(chunk: Uint8Array): void;
31
+ /** Ends stdout: a message without its newline is reported as an error and dropped. */
32
+ end(): void;
33
+ }
34
+ //# sourceMappingURL=lines.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lines.d.ts","sourceRoot":"","sources":["../../src/transports/lines.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAuB,MAAM,wBAAwB,CAAC;AAKlF,MAAM,WAAW,wBAAwB;IACxC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI,CAAC;IACzC,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;CAC9B;AAED;;;GAGG;AACH,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IACnD,2DAA2D;IAC3D,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,kBAAkB,CAAK;IAC/B,OAAO,CAAC,YAAY,CAAmB;IAEvC,YAAY,OAAO,EAAE,wBAAwB,EAE5C;IAED,2CAA2C;IAC3C,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;;;OAIG;IACH,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAuClC;IAED,+EAA+E;IAC/E,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAKlC;IAED,sFAAsF;IACtF,GAAG,IAAI,IAAI,CAMV;CACD"}
@@ -0,0 +1,85 @@
1
+ import { parseJsonRpcMessage } from "../protocol/jsonrpc.js";
2
+ import { DEFAULT_MAX_MESSAGE_BYTES } from "./transport.js";
3
+ const DEFAULT_MAX_STDERR_BYTES = 64 * 1024;
4
+ /**
5
+ * Reads a program's output as MCP's stdio framing: newline-delimited JSON-RPC messages on stdout, and a bounded
6
+ * tail of stderr for diagnostics.
7
+ */
8
+ export class JsonRpcLineReader {
9
+ options;
10
+ /** The bytes of the incomplete message received so far. */
11
+ stdoutChunks = [];
12
+ stdoutPendingBytes = 0;
13
+ stderrBuffer = Buffer.alloc(0);
14
+ constructor(options) {
15
+ this.options = options;
16
+ }
17
+ /** The last `maxStderrBytes` of stderr. */
18
+ get stderr() {
19
+ return this.stderrBuffer.toString("utf8");
20
+ }
21
+ /**
22
+ * Takes the next stdout bytes and reports every complete message, or the error parsing it. Bytes of an
23
+ * incomplete message are kept as chunks and joined once when its newline arrives, so a large message that
24
+ * arrives in many chunks is copied and scanned only once.
25
+ */
26
+ readStdout(chunk) {
27
+ const data = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
28
+ const maxMessageBytes = this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;
29
+ let start = 0;
30
+ while (true) {
31
+ const newline = data.indexOf(0x0a, start);
32
+ if (newline < 0) {
33
+ if (start < data.length) {
34
+ // Copied, since the caller may reuse the chunk's memory.
35
+ this.stdoutChunks.push(Buffer.from(data.subarray(start)));
36
+ this.stdoutPendingBytes += data.length - start;
37
+ }
38
+ if (this.stdoutPendingBytes > maxMessageBytes) {
39
+ this.stdoutChunks = [];
40
+ this.stdoutPendingBytes = 0;
41
+ this.options.onError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));
42
+ }
43
+ return;
44
+ }
45
+ let line = data.subarray(start, newline);
46
+ if (this.stdoutChunks.length > 0) {
47
+ this.stdoutChunks.push(line);
48
+ line = Buffer.concat(this.stdoutChunks, this.stdoutPendingBytes + line.length);
49
+ this.stdoutChunks = [];
50
+ this.stdoutPendingBytes = 0;
51
+ }
52
+ start = newline + 1;
53
+ if (line.length > maxMessageBytes) {
54
+ this.options.onError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));
55
+ continue;
56
+ }
57
+ const text = line.toString("utf8").replace(/\r$/, "");
58
+ if (!text.trim())
59
+ continue;
60
+ try {
61
+ this.options.onMessage(parseJsonRpcMessage(JSON.parse(text)));
62
+ }
63
+ catch (error) {
64
+ this.options.onError(error);
65
+ }
66
+ }
67
+ }
68
+ /** Takes the next stderr bytes into the tail and passes them to `onStderr`. */
69
+ readStderr(chunk) {
70
+ const maxStderrBytes = this.options.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES;
71
+ this.stderrBuffer = Buffer.concat([this.stderrBuffer, chunk]);
72
+ if (this.stderrBuffer.length > maxStderrBytes)
73
+ this.stderrBuffer = this.stderrBuffer.subarray(-maxStderrBytes);
74
+ this.options.onStderr?.(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).toString("utf8"));
75
+ }
76
+ /** Ends stdout: a message without its newline is reported as an error and dropped. */
77
+ end() {
78
+ if (Buffer.concat(this.stdoutChunks).toString("utf8").trim()) {
79
+ this.options.onError(new Error("MCP stdio server closed with an incomplete JSON-RPC message"));
80
+ }
81
+ this.stdoutChunks = [];
82
+ this.stdoutPendingBytes = 0;
83
+ }
84
+ }
85
+ //# sourceMapping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onrpc.ts\";\nimport { DEFAULT_MAX_MESSAGE_BYTES } from \"./transport.ts\";\n\nconst DEFAULT_MAX_STDERR_BYTES = 64 * 1024;\n\nexport interface JsonRpcLineReaderOptions {\n\tmaxMessageBytes?: number;\n\tmaxStderrBytes?: number;\n\t/** Every stderr chunk, decoded as UTF-8. */\n\tonStderr?: (chunk: string) => void;\n\tonMessage(message: JsonRpcMessage): void;\n\tonError(error: unknown): void;\n}\n\n/**\n * Reads a program's output as MCP's stdio framing: newline-delimited JSON-RPC messages on stdout, and a bounded\n * tail of stderr for diagnostics.\n */\nexport class JsonRpcLineReader {\n\tprivate readonly options: JsonRpcLineReaderOptions;\n\t/** The bytes of the incomplete message received so far. */\n\tprivate stdoutChunks: Buffer[] = [];\n\tprivate stdoutPendingBytes = 0;\n\tprivate stderrBuffer = Buffer.alloc(0);\n\n\tconstructor(options: JsonRpcLineReaderOptions) {\n\t\tthis.options = options;\n\t}\n\n\t/** The last `maxStderrBytes` of stderr. */\n\tget stderr(): string {\n\t\treturn this.stderrBuffer.toString(\"utf8\");\n\t}\n\n\t/**\n\t * Takes the next stdout bytes and reports every complete message, or the error parsing it. Bytes of an\n\t * incomplete message are kept as chunks and joined once when its newline arrives, so a large message that\n\t * arrives in many chunks is copied and scanned only once.\n\t */\n\treadStdout(chunk: Uint8Array): void {\n\t\tconst data = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n\t\tconst maxMessageBytes = this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n\t\tlet start = 0;\n\t\twhile (true) {\n\t\t\tconst newline = data.indexOf(0x0a, start);\n\t\t\tif (newline < 0) {\n\t\t\t\tif (start < data.length) {\n\t\t\t\t\t// Copied, since the caller may reuse the chunk's memory.\n\t\t\t\t\tthis.stdoutChunks.push(Buffer.from(data.subarray(start)));\n\t\t\t\t\tthis.stdoutPendingBytes += data.length - start;\n\t\t\t\t}\n\t\t\t\tif (this.stdoutPendingBytes > maxMessageBytes) {\n\t\t\t\t\tthis.stdoutChunks = [];\n\t\t\t\t\tthis.stdoutPendingBytes = 0;\n\t\t\t\t\tthis.options.onError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet line = data.subarray(start, newline);\n\t\t\tif (this.stdoutChunks.length > 0) {\n\t\t\t\tthis.stdoutChunks.push(line);\n\t\t\t\tline = Buffer.concat(this.stdoutChunks, this.stdoutPendingBytes + line.length);\n\t\t\t\tthis.stdoutChunks = [];\n\t\t\t\tthis.stdoutPendingBytes = 0;\n\t\t\t}\n\t\t\tstart = newline + 1;\n\t\t\tif (line.length > maxMessageBytes) {\n\t\t\t\tthis.options.onError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst text = line.toString(\"utf8\").replace(/\\r$/, \"\");\n\t\t\tif (!text.trim()) continue;\n\t\t\ttry {\n\t\t\t\tthis.options.onMessage(parseJsonRpcMessage(JSON.parse(text)));\n\t\t\t} catch (error) {\n\t\t\t\tthis.options.onError(error);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Takes the next stderr bytes into the tail and passes them to `onStderr`. */\n\treadStderr(chunk: Uint8Array): void {\n\t\tconst maxStderrBytes = this.options.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES;\n\t\tthis.stderrBuffer = Buffer.concat([this.stderrBuffer, chunk]);\n\t\tif (this.stderrBuffer.length > maxStderrBytes) this.stderrBuffer = this.stderrBuffer.subarray(-maxStderrBytes);\n\t\tthis.options.onStderr?.(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).toString(\"utf8\"));\n\t}\n\n\t/** Ends stdout: a message without its newline is reported as an error and dropped. */\n\tend(): void {\n\t\tif (Buffer.concat(this.stdoutChunks).toString(\"utf8\").trim()) {\n\t\t\tthis.options.onError(new Error(\"MCP stdio server closed with an incomplete JSON-RPC message\"));\n\t\t}\n\t\tthis.stdoutChunks = [];\n\t\tthis.stdoutPendingBytes = 0;\n\t}\n}\n"]}
@@ -0,0 +1,49 @@
1
+ import { type JsonRpcMessage } from "../protocol/jsonrpc.ts";
2
+ import { type McpTransport, TransportEvents } from "./transport.ts";
3
+ /** A running program's stdio, as a remote process runner provides it. */
4
+ export interface McpPipe {
5
+ write(data: Uint8Array | string): void;
6
+ closeStdin(): void;
7
+ /** Kill the program (and what it started). The pipe owns cleaning up what the program started. */
8
+ close(): void;
9
+ /** Settles when the program has ended, whatever the reason; it must also settle after `close()`. */
10
+ readonly exited: Promise<unknown>;
11
+ }
12
+ /** Handlers `PipeTransportOptions.open` connects to the program's output. */
13
+ export interface McpPipeHandlers {
14
+ onStdout(bytes: Uint8Array): void;
15
+ onStderr(bytes: Uint8Array): void;
16
+ }
17
+ export interface PipeTransportOptions {
18
+ /** Start the program; `onStdout`/`onStderr` receive its output from then on. */
19
+ open(handlers: McpPipeHandlers): Promise<McpPipe>;
20
+ maxMessageBytes?: number;
21
+ maxStderrBytes?: number;
22
+ onStderr?: (chunk: string) => void;
23
+ /** After closing stdin, how long the program may take to exit before `close()` kills it. Default 2000. */
24
+ closeTimeoutMs?: number;
25
+ }
26
+ /**
27
+ * MCP's stdio transport over a program that something else runs, for example on another machine through a remote process runner.
28
+ * The transport closes when the program ends; a rejected `exited` that `close()` did not cause is reported as an
29
+ * error first.
30
+ */
31
+ export declare class PipeTransport extends TransportEvents implements McpTransport {
32
+ readonly options: Readonly<PipeTransportOptions>;
33
+ private readonly lines;
34
+ private pipe;
35
+ private started;
36
+ private closed;
37
+ private ended;
38
+ constructor(options: PipeTransportOptions);
39
+ /** The last `maxStderrBytes` (default 64 KiB) of the program's stderr. */
40
+ get stderr(): string;
41
+ start(): Promise<void>;
42
+ send(message: JsonRpcMessage): Promise<void>;
43
+ close(): Promise<void>;
44
+ /** The program ended: report an unfinished message, then close. */
45
+ private exit;
46
+ /** `exited` rejected: an error unless `close()` caused it, then the same as an exit. */
47
+ private f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CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,KAAK,CAAS;IAEtB,YAAY,OAAO,EAAE,oBAAoB,EAUxC;IAED,0EAA0E;IAC1E,IAAI,MAAM,IAAI,MAAM,CAEnB;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAoB3B;IAEK,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAGjD;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAyB3B;IAED,mEAAmE;IACnE,OAAO,CAAC,IAAI;IAMZ,wFAAwF;IACxF,OAAO,CAAC,IAAI;CAIZ"}
@@ -0,0 +1,96 @@
1
+ import { McpConnectionClosedError } from "../protocol/jsonrpc.js";
2
+ import { JsonRpcLineReader } from "./lines.js";
3
+ import { TransportEvents } from "./transport.js";
4
+ const DEFAULT_CLOSE_TIMEOUT_MS = 2_000;
5
+ /**
6
+ * MCP's stdio transport over a program that something else runs, for example on another machine through a remote process runner.
7
+ * The transport closes when the program ends; a rejected `exited` that `close()` did not cause is reported as an
8
+ * error first.
9
+ */
10
+ export class PipeTransport extends TransportEvents {
11
+ options;
12
+ lines;
13
+ pipe;
14
+ started = false;
15
+ closed = false;
16
+ ended = false;
17
+ constructor(options) {
18
+ super();
19
+ this.options = Object.freeze({ ...options });
20
+ this.lines = new JsonRpcLineReader({
21
+ maxMessageBytes: this.options.maxMessageBytes,
22
+ maxStderrBytes: this.options.maxStderrBytes,
23
+ onStderr: this.options.onStderr,
24
+ onMessage: (message) => this.emitMessage(message),
25
+ onError: (error) => this.emitError(error),
26
+ });
27
+ }
28
+ /** The last `maxStderrBytes` (default 64 KiB) of the program's stderr. */
29
+ get stderr() {
30
+ return this.lines.stderr;
31
+ }
32
+ async start() {
33
+ if (this.started)
34
+ throw new Error("MCP pipe transport already started");
35
+ if (this.closed)
36
+ throw new McpConnectionClosedError();
37
+ this.started = true;
38
+ const pipe = await this.options.open({
39
+ onStdout: (bytes) => this.lines.readStdout(bytes),
40
+ onStderr: (bytes) => this.lines.readStderr(bytes),
41
+ });
42
+ if (this.closed) {
43
+ // close() ran while the program was starting and found nothing to shut down. Nobody else awaits
44
+ // `exited`, and a pipe may reject it after a kill.
45
+ pipe.exited.catch(() => { });
46
+ pipe.close();
47
+ throw new McpConnectionClosedError();
48
+ }
49
+ this.pipe = pipe;
50
+ pipe.exited.then(() => this.exit(), (error) => this.fail(error));
51
+ }
52
+ async send(message) {
53
+ if (!this.pipe || this.closed || this.ended)
54
+ throw new McpConnectionClosedError();
55
+ this.pipe.write(`${JSON.stringify(message)}\n`);
56
+ }
57
+ async close() {
58
+ if (this.closed)
59
+ return;
60
+ this.closed = true;
61
+ const pipe = this.pipe;
62
+ if (!pipe) {
63
+ this.emitClose();
64
+ return;
65
+ }
66
+ if (this.ended)
67
+ return;
68
+ // Shutdown per the spec: close stdin and let the program exit, then kill it.
69
+ pipe.closeStdin();
70
+ let timer;
71
+ const exitedInTime = await Promise.race([
72
+ pipe.exited.then(() => true, () => true),
73
+ new Promise((resolve) => {
74
+ timer = setTimeout(() => resolve(false), this.options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS);
75
+ }),
76
+ ]);
77
+ clearTimeout(timer);
78
+ if (exitedInTime)
79
+ return;
80
+ pipe.close();
81
+ await pipe.exited.catch(() => { });
82
+ }
83
+ /** The program ended: report an unfinished message, then close. */
84
+ exit() {
85
+ this.ended = true;
86
+ this.lines.end();
87
+ this.emitClose();
88
+ }
89
+ /** `exited` rejected: an error unless `close()` caused it, then the same as an exit. */
90
+ fail(error) {
91
+ if (!this.closed)
92
+ this.emitError(error);
93
+ this.exit();
94
+ }
95
+ }
96
+ //# sourceMappingURL=pipe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipe.js","sourceRoot":"","sources":["../../src/transports/pipe.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AACvF,OAAO,EAAE,iBAAiB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A6E;QAC7E,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,IAAI,KAAgD,CAAC;QACrD,MAAM,YAAY,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;YACvC,IAAI,CAAC,MAAM,CAAC,IAAI,CACf,GAAG,EAAE,CAAC,IAAI,EACV,GAAG,EAAE,CAAC,IAAI,CACV;YACD,IAAI,OAAO,CAAQ,CAAC,OAAO,EAAE,EAAE;gBAC9B,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,cAAc,IAAI,wBAAwB,CAAC,CAAC;YACnG,CAAC,CAAC;SACF,CAAC,CAAC;QACH,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,IAAI,YAAY;YAAE,OAAO;QACzB,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACnC,CAAC;IAED,mEAAmE;IAC3D,IAAI;QACX,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACjB,IAAI,CAAC,SAAS,EAAE,CAAC;IAClB,CAAC;IAED,wFAAwF;IAChF,IAAI,CAAC,KAAc;QAC1B,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACxC,IAAI,CAAC,IAAI,EAAE,CAAC;IACb,CAAC;CACD","sourcesContent":["import { type JsonRpcMessage, McpConnectionClosedError } from \"../protocol/jsonrpc.ts\";\nimport { JsonRpcLineReader } from \"./lines.ts\";\nimport { type McpTransport, TransportEvents } from \"./transport.ts\";\n\nconst DEFAULT_CLOSE_TIMEOUT_MS = 2_000;\n\n/** A running program's stdio, as a remote process runner provides it. */\nexport interface McpPipe {\n\twrite(data: Uint8Array | string): void;\n\tcloseStdin(): void;\n\t/** Kill the program (and what it started). The pipe owns cleaning up what the program started. */\n\tclose(): void;\n\t/** Settles when the program has ended, whatever the reason; it must also settle after `close()`. */\n\treadonly exited: Promise<unknown>;\n}\n\n/** Handlers `PipeTransportOptions.open` connects to the program's output. */\nexport interface McpPipeHandlers {\n\tonStdout(bytes: Uint8Array): void;\n\tonStderr(bytes: Uint8Array): void;\n}\n\nexport interface PipeTransportOptions {\n\t/** Start the program; `onStdout`/`onStderr` receive its output from then on. */\n\topen(handlers: McpPipeHandlers): Promise<McpPipe>;\n\tmaxMessageBytes?: number;\n\tmaxStderrBytes?: number;\n\tonStderr?: (chunk: string) => void;\n\t/** After closing stdin, how long the program may take to exit before `close()` kills it. Default 2000. */\n\tcloseTimeoutMs?: number;\n}\n\n/**\n * MCP's stdio transport over a program that something else runs, for example on another machine through a remote process runner.\n * The transport closes when the program ends; a rejected `exited` that `close()` did not cause is reported as an\n * error first.\n */\nexport class PipeTransport extends TransportEvents implements McpTransport {\n\treadonly options: Readonly<PipeTransportOptions>;\n\tprivate readonly lines: JsonRpcLineReader;\n\tprivate pipe: McpPipe | undefined;\n\tprivate started = false;\n\tprivate closed = false;\n\tprivate ended = false;\n\n\tconstructor(options: PipeTransportOptions) {\n\t\tsuper();\n\t\tthis.options = Object.freeze({ ...options });\n\t\tthis.lines = new JsonRpcLineReader({\n\t\t\tmaxMessageBytes: this.options.maxMessageBytes,\n\t\t\tmaxStderrBytes: this.options.maxStderrBytes,\n\t\t\tonStderr: this.options.onStderr,\n\t\t\tonMessage: (message) => this.emitMessage(message),\n\t\t\tonError: (error) => this.emitError(error),\n\t\t});\n\t}\n\n\t/** The last `maxStderrBytes` (default 64 KiB) of the program's stderr. */\n\tget stderr(): string {\n\t\treturn this.lines.stderr;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.started) throw new Error(\"MCP pipe transport already started\");\n\t\tif (this.closed) throw new McpConnectionClosedError();\n\t\tthis.started = true;\n\t\tconst pipe = await this.options.open({\n\t\t\tonStdout: (bytes) => this.lines.readStdout(bytes),\n\t\t\tonStderr: (bytes) => this.lines.readStderr(bytes),\n\t\t});\n\t\tif (this.closed) {\n\t\t\t// close() ran while the program was starting and found nothing to shut down. Nobody else awaits\n\t\t\t// `exited`, and a pipe may reject it after a kill.\n\t\t\tpipe.exited.catch(() => {});\n\t\t\tpipe.close();\n\t\t\tthrow new McpConnectionClosedError();\n\t\t}\n\t\tthis.pipe = pipe;\n\t\tpipe.exited.then(\n\t\t\t() => this.exit(),\n\t\t\t(error: unknown) => this.fail(error),\n\t\t);\n\t}\n\n\tasync send(message: JsonRpcMessage): Promise<void> {\n\t\tif (!this.pipe || this.closed || this.ended) throw new McpConnectionClosedError();\n\t\tthis.pipe.write(`${JSON.stringify(message)}\\n`);\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tconst pipe = this.pipe;\n\t\tif (!pipe) {\n\t\t\tthis.emitClose();\n\t\t\treturn;\n\t\t}\n\t\tif (this.ended) return;\n\t\t// Shutdown per the spec: close stdin and let the program exit, then kill it.\n\t\tpipe.closeStdin();\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst exitedInTime = await Promise.race([\n\t\t\tpipe.exited.then(\n\t\t\t\t() => true,\n\t\t\t\t() => true,\n\t\t\t),\n\t\t\tnew Promise<false>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(false), this.options.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS);\n\t\t\t}),\n\t\t]);\n\t\tclearTimeout(timer);\n\t\tif (exitedInTime) return;\n\t\tpipe.close();\n\t\tawait pipe.exited.catch(() => {});\n\t}\n\n\t/** The program ended: report an unfinished message, then close. */\n\tprivate exit(): void {\n\t\tthis.ended = true;\n\t\tthis.lines.end();\n\t\tthis.emitClose();\n\t}\n\n\t/** `exited` rejected: an error unless `close()` caused it, then the same as an exit. */\n\tprivate fail(error: unknown): void {\n\t\tif (!this.closed) this.emitError(error);\n\t\tthis.exit();\n\t}\n}\n"]}
@@ -16,8 +16,7 @@ export interface StdioTransportOptions {
16
16
  export declare class StdioTransport extends TransportEvents implements McpTransport {
17
17
  readonly options: Readonly<StdioTransportOptions>;
18
18
  private child;
19
- private stdoutBuffer;
20
- private stderrBuffer;
19
+ private readonly lines;
21
20
  private started;
22
21
  private closed;
23
22
  constructor(options: StdioTransportOptions);
@@ -26,7 +25,5 @@ export declare class StdioTransport extends TransportEvents implements McpTransp
26
25
  start(): Promise<void>;
27
26
  send(message: JsonRpcMessage): Promise<void>;
28
27
  close(): Promise<void>;
29
- private handleStdout;
30
- private handleStderr;
31
28
  }
32
29
  //# sourceMappingURL=stdio.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/transports/stdio.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,cAAc,EAAiD,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EAA6B,KAAK,YAAY,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAkD/F,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,+FAA+F;IAC/F,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,cAAe,SAAQ,eAAgB,YAAW,YAAY;IAC1E,QAAQ,CAAC,OAAO,EAAE,QAAQ,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