@diffra-ai/mcp 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.
Files changed (125) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +22 -0
  3. package/README.md +190 -2
  4. package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
  5. package/dist/auth-provider.d.ts +19 -0
  6. package/dist/auth-provider.d.ts.map +1 -0
  7. package/dist/auth-provider.js +2 -0
  8. package/dist/auth-provider.js.map +1 -0
  9. package/dist/client.d.ts +89 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +461 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/config.d.ts +117 -0
  14. package/dist/config.d.ts.map +1 -0
  15. package/dist/config.js +153 -0
  16. package/dist/config.js.map +1 -0
  17. package/dist/index.d.ts +16 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +14 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/input-schema.d.ts +7 -0
  22. package/dist/input-schema.d.ts.map +1 -0
  23. package/dist/input-schema.js +13 -0
  24. package/dist/input-schema.js.map +1 -0
  25. package/dist/model-content.d.ts +19 -0
  26. package/dist/model-content.d.ts.map +1 -0
  27. package/dist/model-content.js +67 -0
  28. package/dist/model-content.js.map +1 -0
  29. package/dist/naming.d.ts +23 -0
  30. package/dist/naming.d.ts.map +1 -0
  31. package/dist/naming.js +37 -0
  32. package/dist/naming.js.map +1 -0
  33. package/dist/oauth/auth-provider.d.ts +52 -0
  34. package/dist/oauth/auth-provider.d.ts.map +1 -0
  35. package/dist/oauth/auth-provider.js +97 -0
  36. package/dist/oauth/auth-provider.js.map +1 -0
  37. package/dist/oauth/callback.d.ts +48 -0
  38. package/dist/oauth/callback.d.ts.map +1 -0
  39. package/dist/oauth/callback.js +119 -0
  40. package/dist/oauth/callback.js.map +1 -0
  41. package/dist/oauth/client-settings.d.ts +107 -0
  42. package/dist/oauth/client-settings.d.ts.map +1 -0
  43. package/dist/oauth/client-settings.js +114 -0
  44. package/dist/oauth/client-settings.js.map +1 -0
  45. package/dist/oauth/discovery.d.ts +30 -0
  46. package/dist/oauth/discovery.d.ts.map +1 -0
  47. package/dist/oauth/discovery.js +156 -0
  48. package/dist/oauth/discovery.js.map +1 -0
  49. package/dist/oauth/errors.d.ts +32 -0
  50. package/dist/oauth/errors.d.ts.map +1 -0
  51. package/dist/oauth/errors.js +58 -0
  52. package/dist/oauth/errors.js.map +1 -0
  53. package/dist/oauth/flow.d.ts +112 -0
  54. package/dist/oauth/flow.d.ts.map +1 -0
  55. package/dist/oauth/flow.js +360 -0
  56. package/dist/oauth/flow.js.map +1 -0
  57. package/dist/oauth/index.d.ts +11 -0
  58. package/dist/oauth/index.d.ts.map +1 -0
  59. package/dist/oauth/index.js +9 -0
  60. package/dist/oauth/index.js.map +1 -0
  61. package/dist/oauth/loopback.d.ts +51 -0
  62. package/dist/oauth/loopback.d.ts.map +1 -0
  63. package/dist/oauth/loopback.js +98 -0
  64. package/dist/oauth/loopback.js.map +1 -0
  65. package/dist/oauth/provider.d.ts +62 -0
  66. package/dist/oauth/provider.d.ts.map +1 -0
  67. package/dist/oauth/provider.js +118 -0
  68. package/dist/oauth/provider.js.map +1 -0
  69. package/dist/oauth/sign-in.d.ts +73 -0
  70. package/dist/oauth/sign-in.d.ts.map +1 -0
  71. package/dist/oauth/sign-in.js +182 -0
  72. package/dist/oauth/sign-in.js.map +1 -0
  73. package/dist/oauth/types.d.ts +83 -0
  74. package/dist/oauth/types.d.ts.map +1 -0
  75. package/dist/oauth/types.js +113 -0
  76. package/dist/oauth/types.js.map +1 -0
  77. package/dist/output-limit.d.ts +24 -0
  78. package/dist/output-limit.d.ts.map +1 -0
  79. package/dist/output-limit.js +58 -0
  80. package/dist/output-limit.js.map +1 -0
  81. package/dist/protocol/content.d.ts +83 -0
  82. package/dist/protocol/content.d.ts.map +1 -0
  83. package/dist/protocol/content.js +41 -0
  84. package/dist/protocol/content.js.map +1 -0
  85. package/dist/protocol/jsonrpc.d.ts +59 -0
  86. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  87. package/dist/protocol/jsonrpc.js +67 -0
  88. package/dist/protocol/jsonrpc.js.map +1 -0
  89. package/dist/protocol/types.d.ts +123 -0
  90. package/dist/protocol/types.d.ts.map +1 -0
  91. package/dist/protocol/types.js +7 -0
  92. package/dist/protocol/types.js.map +1 -0
  93. package/dist/result-schema.d.ts +10 -0
  94. package/dist/result-schema.d.ts.map +1 -0
  95. package/dist/result-schema.js +78 -0
  96. package/dist/result-schema.js.map +1 -0
  97. package/dist/testing/index.d.ts +2 -0
  98. package/dist/testing/index.d.ts.map +1 -0
  99. package/dist/testing/index.js +2 -0
  100. package/dist/testing/index.js.map +1 -0
  101. package/dist/transports/in-memory.d.ts +19 -0
  102. package/dist/transports/in-memory.d.ts.map +1 -0
  103. package/dist/transports/in-memory.js +50 -0
  104. package/dist/transports/in-memory.js.map +1 -0
  105. package/dist/transports/lines.d.ts +34 -0
  106. package/dist/transports/lines.d.ts.map +1 -0
  107. package/dist/transports/lines.js +85 -0
  108. package/dist/transports/lines.js.map +1 -0
  109. package/dist/transports/pipe.d.ts +49 -0
  110. package/dist/transports/pipe.d.ts.map +1 -0
  111. package/dist/transports/pipe.js +96 -0
  112. package/dist/transports/pipe.js.map +1 -0
  113. package/dist/transports/stdio.d.ts +29 -0
  114. package/dist/transports/stdio.d.ts.map +1 -0
  115. package/dist/transports/stdio.js +170 -0
  116. package/dist/transports/stdio.js.map +1 -0
  117. package/dist/transports/streamable-http.d.ts +103 -0
  118. package/dist/transports/streamable-http.d.ts.map +1 -0
  119. package/dist/transports/streamable-http.js +531 -0
  120. package/dist/transports/streamable-http.js.map +1 -0
  121. package/dist/transports/transport.d.ts +36 -0
  122. package/dist/transports/transport.d.ts.map +1 -0
  123. package/dist/transports/transport.js +38 -0
  124. package/dist/transports/transport.js.map +1 -0
  125. package/package.json +59 -5
@@ -0,0 +1,113 @@
1
+ /*
2
+ * Adapted from modelcontextprotocol/typescript-sdk v1.29.0.
3
+ * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.
4
+ * Modified to use dependency-free structural validation.
5
+ */
6
+ import { isObject } from "../protocol/jsonrpc.js";
7
+ function object(value, name) {
8
+ if (!isObject(value))
9
+ throw new Error(`Invalid ${name}`);
10
+ return value;
11
+ }
12
+ /** Drops `undefined` values so optional fields are absent rather than present-but-undefined. */
13
+ function compact(value) {
14
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
15
+ }
16
+ function requiredString(value, name) {
17
+ if (typeof value !== "string" || value.length === 0)
18
+ throw new Error(`Invalid ${name}`);
19
+ return value;
20
+ }
21
+ /** Treats `null` and `""` as absent: servers send them for fields they have no value for, like `scope: ""`. */
22
+ function absent(value) {
23
+ return value === undefined || value === null || value === "";
24
+ }
25
+ function optionalString(value, name) {
26
+ if (absent(value))
27
+ return undefined;
28
+ return requiredString(value, name);
29
+ }
30
+ function optionalStrings(value, name) {
31
+ if (value === undefined || value === null)
32
+ return undefined;
33
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
34
+ throw new Error(`Invalid ${name}`);
35
+ return [...value];
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
+ */
41
+ function safeUrl(value, name) {
42
+ const text = requiredString(value, name);
43
+ // URL parsing throws a `TypeError`, which discovery reserves for network failures.
44
+ if (!URL.canParse(text) || !isHttpUrl(new URL(text)))
45
+ throw new Error(`Invalid ${name}`);
46
+ return text;
47
+ }
48
+ export function isHttpUrl(url) {
49
+ return url.protocol === "http:" || url.protocol === "https:";
50
+ }
51
+ function optionalUrl(value, name) {
52
+ return absent(value) ? undefined : safeUrl(value, name);
53
+ }
54
+ export function parseProtectedResourceMetadata(value) {
55
+ const input = object(value, "OAuth protected resource metadata");
56
+ return compact({
57
+ ...input,
58
+ resource: safeUrl(input.resource, "OAuth protected resource metadata resource"),
59
+ authorization_servers: optionalStrings(input.authorization_servers, "authorization_servers")?.map((url) => safeUrl(url, "authorization server URL")),
60
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported"),
61
+ });
62
+ }
63
+ export function parseAuthorizationServerMetadata(value) {
64
+ const input = object(value, "authorization server metadata");
65
+ const responseTypes = optionalStrings(input.response_types_supported, "response_types_supported");
66
+ if (!responseTypes)
67
+ throw new Error("Invalid response_types_supported");
68
+ return compact({
69
+ ...input,
70
+ issuer: safeUrl(input.issuer, "authorization server issuer"),
71
+ authorization_endpoint: safeUrl(input.authorization_endpoint, "authorization endpoint"),
72
+ token_endpoint: safeUrl(input.token_endpoint, "token endpoint"),
73
+ registration_endpoint: optionalUrl(input.registration_endpoint, "registration endpoint"),
74
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported"),
75
+ response_types_supported: responseTypes,
76
+ grant_types_supported: optionalStrings(input.grant_types_supported, "grant_types_supported"),
77
+ token_endpoint_auth_methods_supported: optionalStrings(input.token_endpoint_auth_methods_supported, "token_endpoint_auth_methods_supported"),
78
+ code_challenge_methods_supported: optionalStrings(input.code_challenge_methods_supported, "code_challenge_methods_supported"),
79
+ client_id_metadata_document_supported: typeof input.client_id_metadata_document_supported === "boolean"
80
+ ? input.client_id_metadata_document_supported
81
+ : undefined,
82
+ authorization_response_iss_parameter_supported: typeof input.authorization_response_iss_parameter_supported === "boolean"
83
+ ? input.authorization_response_iss_parameter_supported
84
+ : undefined,
85
+ });
86
+ }
87
+ export function parseOAuthTokens(value) {
88
+ const input = object(value, "OAuth token response");
89
+ // `Number(null)` is 0, which would mark the token as expired at once.
90
+ const expires = absent(input.expires_in) ? undefined : Number(input.expires_in);
91
+ if (expires !== undefined && !Number.isFinite(expires))
92
+ throw new Error("Invalid expires_in");
93
+ return compact({
94
+ access_token: requiredString(input.access_token, "access_token"),
95
+ token_type: requiredString(input.token_type, "token_type"),
96
+ expires_in: expires,
97
+ scope: optionalString(input.scope, "scope"),
98
+ refresh_token: optionalString(input.refresh_token, "refresh_token"),
99
+ id_token: optionalString(input.id_token, "id_token"),
100
+ });
101
+ }
102
+ export function parseClientInformation(value) {
103
+ const input = object(value, "OAuth client registration response");
104
+ return compact({
105
+ ...input,
106
+ client_id: requiredString(input.client_id, "client_id"),
107
+ client_secret: optionalString(input.client_secret, "client_secret"),
108
+ client_id_issued_at: typeof input.client_id_issued_at === "number" ? input.client_id_issued_at : undefined,
109
+ client_secret_expires_at: typeof input.client_secret_expires_at === "number" ? input.client_secret_expires_at : undefined,
110
+ redirect_uris: optionalStrings(input.redirect_uris, "redirect_uris") ?? [],
111
+ });
112
+ }
113
+ //# sourceMappingURL=types.js.map
@@ -0,0 +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,EA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AK,EAAE,OAAO,CAAC;QAC3C,aAAa,EAAE,cAAc,CAAC,KAAK,CAAC,aAAa,EAAE,eAAe,CAAC;QACnE,QAAQ,EAAE,cAAc,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;KACpD,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACpD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,EAAE,oCAAoC,CAAC,CAAC;IAClE,OAAO,OAAO,CAAC;QACd,GAAI,KAAwC;QAC5C,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC;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 THIRD_PARTY_NOTICES/.\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
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AG,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACvD,MAAM,YAAY,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3F,kEAAkE;IAClE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,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,83 @@
1
+ export interface ContentAnnotations {
2
+ audience?: ("user" | "assistant")[];
3
+ priority?: number;
4
+ lastModified?: string;
5
+ }
6
+ export interface TextContent {
7
+ type: "text";
8
+ text: string;
9
+ annotations?: ContentAnnotations;
10
+ _meta?: Record<string, unknown>;
11
+ }
12
+ export interface ImageContent {
13
+ type: "image";
14
+ data: string;
15
+ mimeType: string;
16
+ annotations?: ContentAnnotations;
17
+ _meta?: Record<string, unknown>;
18
+ }
19
+ export interface AudioContent {
20
+ type: "audio";
21
+ data: string;
22
+ mimeType: string;
23
+ annotations?: ContentAnnotations;
24
+ _meta?: Record<string, unknown>;
25
+ }
26
+ export interface ResourceLinkContent {
27
+ type: "resource_link";
28
+ uri: string;
29
+ name: string;
30
+ title?: string;
31
+ description?: string;
32
+ mimeType?: string;
33
+ size?: number;
34
+ annotations?: ContentAnnotations;
35
+ _meta?: Record<string, unknown>;
36
+ }
37
+ export interface TextResourceContents {
38
+ uri: string;
39
+ mimeType?: string;
40
+ text: string;
41
+ _meta?: Record<string, unknown>;
42
+ }
43
+ export interface BlobResourceContents {
44
+ uri: string;
45
+ mimeType?: string;
46
+ blob: string;
47
+ _meta?: Record<string, unknown>;
48
+ }
49
+ export interface EmbeddedResourceContent {
50
+ type: "resource";
51
+ resource: TextResourceContents | BlobResourceContents;
52
+ annotations?: ContentAnnotations;
53
+ _meta?: Record<string, unknown>;
54
+ }
55
+ export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLinkContent | EmbeddedResourceContent;
56
+ export interface CallToolResult {
57
+ content: ContentBlock[];
58
+ /** Any JSON value, including arrays and `null` (MCP 2026-07-28; earlier revisions allowed only objects). */
59
+ structuredContent?: unknown;
60
+ isError?: boolean;
61
+ _meta?: Record<string, unknown>;
62
+ }
63
+ /**
64
+ * Tool result content in the shape LLM APIs accept: text and base64 images. Matches the
65
+ * `TextContent` and `ImageContent` types of `@diffra-ai/ai`.
66
+ */
67
+ export type LlmContent = {
68
+ type: "text";
69
+ text: string;
70
+ } | {
71
+ type: "image";
72
+ data: string;
73
+ mimeType: string;
74
+ };
75
+ /**
76
+ * Convert a tool result to text and image content for a model. Text and images pass through,
77
+ * embedded text resources become text, embedded image resources become images, and other blocks
78
+ * (audio, resource links, binary resources) become a short text placeholder. A result without
79
+ * content blocks but with `structuredContent` becomes its JSON, since servers should, but do not
80
+ * always, mirror structured results as text.
81
+ */
82
+ export declare function toLlmContent(result: Pick<CallToolResult, "content" | "structuredContent">): LlmContent[];
83
+ //# sourceMappingURL=content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../src/protocol/content.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,EAAE,CAAC,MAAM,GAAG,WAAW,CAAC,EAAE,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;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W,GAAG,YAAY,GAAG,YAAY,GAAG,mBAAmB,GAAG,uBAAuB,CAAC;AAErH,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,4GAA4G;IAC5G,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AA4B5G;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,cAAc,EAAE,SAAS,GAAG,mBAAmB,CAAC,GAAG,UAAU,EAAE,CAMxG"}
@@ -0,0 +1,41 @@
1
+ function blockToLlmContent(block) {
2
+ switch (block.type) {
3
+ case "text":
4
+ return { type: "text", text: block.text };
5
+ case "image":
6
+ return { type: "image", data: block.data, mimeType: block.mimeType };
7
+ case "audio":
8
+ return { type: "text", text: `[audio ${block.mimeType} omitted]` };
9
+ case "resource_link":
10
+ return { type: "text", text: `${block.name}: ${block.uri}` };
11
+ case "resource": {
12
+ const resource = block.resource;
13
+ if ("text" in resource)
14
+ return { type: "text", text: resource.text };
15
+ if (resource.mimeType?.startsWith("image/")) {
16
+ return { type: "image", data: resource.blob, mimeType: resource.mimeType };
17
+ }
18
+ return {
19
+ type: "text",
20
+ text: `[binary resource ${resource.uri} (${resource.mimeType ?? "unknown type"}) omitted]`,
21
+ };
22
+ }
23
+ default:
24
+ return { type: "text", text: `[unsupported MCP content ${block.type}]` };
25
+ }
26
+ }
27
+ /**
28
+ * Convert a tool result to text and image content for a model. Text and images pass through,
29
+ * embedded text resources become text, embedded image resources become images, and other blocks
30
+ * (audio, resource links, binary resources) become a short text placeholder. A result without
31
+ * content blocks but with `structuredContent` becomes its JSON, since servers should, but do not
32
+ * always, mirror structured results as text.
33
+ */
34
+ export function toLlmContent(result) {
35
+ const content = (result.content ?? []).map(blockToLlmContent);
36
+ if (content.length === 0 && result.structuredContent !== undefined) {
37
+ content.push({ type: "text", text: JSON.stringify(result.structuredContent, null, 2) });
38
+ }
39
+ return content;
40
+ }
41
+ //# sourceMappingURL=content.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/protocol/content.ts"],"names":[],"mappings":"AA8EA,SAAS,iBAAiB,CAAC,KAAmB;IAC7C,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,MAAM;YACV,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC;QAC3C,KAAK,OAAO;YACX,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;QACtE,KAAK,OAAO;YACX,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,KAAK,CAAC,QAAQ,WAAW,EAAE,CAAC;QACpE,KAAK,eAAe;YACnB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC;QAC9D,KAAK,UAAU,EAAE,CAAC;YACjB,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;YAChC,IAAI,MAAM,IAAI,QAAQ;gBAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;YACrE,IAAI,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAC7C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC;YAC5E,CAAC;YACD,OAAO;gBACN,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,oBAAoB,QAAQ,CAAC,GAAG,KAAK,QAAQ,CAAC,QAAQ,IAAI,cAAc,YAAY;aAC1F,CAAC;QACH,CAAC;QACD;YACC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,4BAA6B,KAA0B,CAAC,IAAI,GAAG,EAAE,CAAC;IACjG,CAAC;AACF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAC,MAA6D;IACzF,MAAM,OAAO,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC9D,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,MAAM,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QACpE,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACzF,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["export interface ContentAnnotations {\n\taudience?: (\"user\" | \"assistant\")[];\n\tpriority?: number;\n\tlastModified?: string;\n}\n\nexport interface TextContent {\n\ttype: \"text\";\n\ttext: string;\n\tannotations?: ContentAnnotations;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface ImageContent {\n\ttype: \"image\";\n\tdata: string;\n\tmimeType: string;\n\tannotations?: ContentAnnotations;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface AudioContent {\n\ttype: \"audio\";\n\tdata: string;\n\tmimeType: string;\n\tannotations?: ContentAnnotations;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface ResourceLinkContent {\n\ttype: \"resource_link\";\n\turi: string;\n\tname: string;\n\ttitle?: string;\n\tdescription?: string;\n\tmimeType?: string;\n\tsize?: number;\n\tannotations?: ContentAnnotations;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface TextResourceContents {\n\turi: string;\n\tmimeType?: string;\n\ttext: string;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface BlobResourceContents {\n\turi: string;\n\tmimeType?: string;\n\tblob: string;\n\t_meta?: Record<string, unknown>;\n}\n\nexport interface EmbeddedResourceContent {\n\ttype: \"resource\";\n\tresource: TextResourceContents | BlobResourceContents;\n\tannotations?: ContentAnnotations;\n\t_meta?: Record<string, unknown>;\n}\n\nexport type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLinkContent | EmbeddedResourceContent;\n\nexport interface CallToolResult {\n\tcontent: ContentBlock[];\n\t/** Any JSON value, including arrays and `null` (MCP 2026-07-28; earlier revisions allowed only objects). */\n\tstructuredContent?: unknown;\n\tisError?: boolean;\n\t_meta?: Record<string, unknown>;\n}\n\n/**\n * Tool result content in the shape LLM APIs accept: text and base64 images. Matches the\n * `TextContent` and `ImageContent` types of `@diffra-ai/ai`.\n */\nexport type LlmContent = { type: \"text\"; text: string } | { type: \"image\"; data: string; mimeType: string };\n\nfunction blockToLlmContent(block: ContentBlock): LlmContent {\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\treturn { type: \"text\", text: block.text };\n\t\tcase \"image\":\n\t\t\treturn { type: \"image\", data: block.data, mimeType: block.mimeType };\n\t\tcase \"audio\":\n\t\t\treturn { type: \"text\", text: `[audio ${block.mimeType} omitted]` };\n\t\tcase \"resource_link\":\n\t\t\treturn { type: \"text\", text: `${block.name}: ${block.uri}` };\n\t\tcase \"resource\": {\n\t\t\tconst resource = block.resource;\n\t\t\tif (\"text\" in resource) return { type: \"text\", text: resource.text };\n\t\t\tif (resource.mimeType?.startsWith(\"image/\")) {\n\t\t\t\treturn { type: \"image\", data: resource.blob, mimeType: resource.mimeType };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `[binary resource ${resource.uri} (${resource.mimeType ?? \"unknown type\"}) omitted]`,\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\treturn { type: \"text\", text: `[unsupported MCP content ${(block as { type: string }).type}]` };\n\t}\n}\n\n/**\n * Convert a tool result to text and image content for a model. Text and images pass through,\n * embedded text resources become text, embedded image resources become images, and other blocks\n * (audio, resource links, binary resources) become a short text placeholder. A result without\n * content blocks but with `structuredContent` becomes its JSON, since servers should, but do not\n * always, mirror structured results as text.\n */\nexport function toLlmContent(result: Pick<CallToolResult, \"content\" | \"structuredContent\">): LlmContent[] {\n\tconst content = (result.content ?? []).map(blockToLlmContent);\n\tif (content.length === 0 && result.structuredContent !== undefined) {\n\t\tcontent.push({ type: \"text\", text: JSON.stringify(result.structuredContent, null, 2) });\n\t}\n\treturn content;\n}\n"]}
@@ -0,0 +1,59 @@
1
+ export type JsonRpcId = string | number;
2
+ export interface JsonRpcRequest {
3
+ jsonrpc: "2.0";
4
+ id: JsonRpcId;
5
+ method: string;
6
+ params?: unknown;
7
+ }
8
+ export interface JsonRpcNotification {
9
+ jsonrpc: "2.0";
10
+ method: string;
11
+ params?: unknown;
12
+ }
13
+ export interface JsonRpcErrorObject {
14
+ code: number;
15
+ message: string;
16
+ data?: unknown;
17
+ }
18
+ export interface JsonRpcSuccessResponse {
19
+ jsonrpc: "2.0";
20
+ id: JsonRpcId;
21
+ result: unknown;
22
+ }
23
+ export interface JsonRpcErrorResponse {
24
+ jsonrpc: "2.0";
25
+ id: JsonRpcId;
26
+ error: JsonRpcErrorObject;
27
+ }
28
+ export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
29
+ export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;
30
+ export declare const JSON_RPC_ERROR_CODES: {
31
+ readonly parseError: -32700;
32
+ readonly invalidRequest: -32600;
33
+ readonly methodNotFound: -32601;
34
+ readonly invalidParams: -32602;
35
+ readonly internalError: -32603;
36
+ };
37
+ export declare class McpError extends Error {
38
+ readonly code: number;
39
+ readonly data: unknown;
40
+ constructor(code: number, message: string, data?: unknown);
41
+ }
42
+ export declare class McpConnectionClosedError extends Error {
43
+ constructor(message?: string);
44
+ }
45
+ export declare class McpTimeoutError extends Error {
46
+ readonly timeoutMs: number;
47
+ constructor(timeoutMs: number);
48
+ }
49
+ export declare class McpAbortError extends Error {
50
+ constructor(message?: string);
51
+ }
52
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
53
+ export declare function toError(value: unknown): Error;
54
+ export declare function isJsonRpcId(value: unknown): value is JsonRpcId;
55
+ export declare function isJsonRpcRequest(message: unknown): message is JsonRpcRequest;
56
+ export declare function isJsonRpcNotification(message: unknown): message is JsonRpcNotification;
57
+ export declare function isJsonRpcResponse(message: unknown): message is JsonRpcResponse;
58
+ export declare function parseJsonRpcMessage(value: unknown): JsonRpcMessage;
59
+ //# sourceMappingURL=jsonrpc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonrpc.d.ts","sourceRoot":"","sources":["../../src/protocol/jsonrpc.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAExC,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,KAAK,CAAC;IACf,EAAE,EAAE,SAAS,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IACnC,OAAO,EAAE,KAAK,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IA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K,CAE7C;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,cAAc,CAI5E;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,mBAAmB,CAEtF;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,eAAe,CAK9E;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,CAGlE"}
@@ -0,0 +1,67 @@
1
+ export const JSON_RPC_ERROR_CODES = {
2
+ parseError: -32700,
3
+ invalidRequest: -32600,
4
+ methodNotFound: -32601,
5
+ invalidParams: -32602,
6
+ internalError: -32603,
7
+ };
8
+ export class McpError extends Error {
9
+ code;
10
+ data;
11
+ constructor(code, message, data) {
12
+ super(message);
13
+ this.name = "McpError";
14
+ this.code = code;
15
+ this.data = data;
16
+ }
17
+ }
18
+ export class McpConnectionClosedError extends Error {
19
+ constructor(message = "MCP connection closed") {
20
+ super(message);
21
+ this.name = "McpConnectionClosedError";
22
+ }
23
+ }
24
+ export class McpTimeoutError extends Error {
25
+ timeoutMs;
26
+ constructor(timeoutMs) {
27
+ super(`MCP request timed out after ${timeoutMs}ms`);
28
+ this.name = "McpTimeoutError";
29
+ this.timeoutMs = timeoutMs;
30
+ }
31
+ }
32
+ export class McpAbortError extends Error {
33
+ constructor(message = "MCP request aborted") {
34
+ super(message);
35
+ this.name = "AbortError";
36
+ }
37
+ }
38
+ export function isObject(value) {
39
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40
+ }
41
+ export function toError(value) {
42
+ return value instanceof Error ? value : new Error(String(value));
43
+ }
44
+ export function isJsonRpcId(value) {
45
+ return typeof value === "string" || (typeof value === "number" && Number.isFinite(value));
46
+ }
47
+ export function isJsonRpcRequest(message) {
48
+ return (isObject(message) && message.jsonrpc === "2.0" && isJsonRpcId(message.id) && typeof message.method === "string");
49
+ }
50
+ export function isJsonRpcNotification(message) {
51
+ return isObject(message) && message.jsonrpc === "2.0" && !("id" in message) && typeof message.method === "string";
52
+ }
53
+ export function isJsonRpcResponse(message) {
54
+ if (!isObject(message) || message.jsonrpc !== "2.0" || !isJsonRpcId(message.id))
55
+ return false;
56
+ if ("result" in message)
57
+ return !("error" in message);
58
+ if (!("error" in message) || !isObject(message.error))
59
+ return false;
60
+ return typeof message.error.code === "number" && typeof message.error.message === "string";
61
+ }
62
+ export function parseJsonRpcMessage(value) {
63
+ if (isJsonRpcRequest(value) || isJsonRpcNotification(value) || isJsonRpcResponse(value))
64
+ return value;
65
+ throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid JSON-RPC message");
66
+ }
67
+ //# sourceMappingURL=jsonrpc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonrpc.js","sourceRoot":"","sources":["../../src/protocol/jsonrpc.ts"],"names":[],"mappings":"AAoCA,MAAM,CAAC,MAAM,oBAAoB,GAAG;IACnC,UAAU,EAAE,CAAC,KAAK;IAClB,cAAc,EAAE,CAAC,KAAK;IACtB,cAAc,EAAE,CAAC,KAAK;IACtB,aAAa,EAAE,CAAC,KAAK;IACrB,aAAa,EAAE,CAAC,KAAK;CACZ,CAAC;AAEX,MAAM,OAAO,QAAS,SAAQ,KAAK;IACzB,IAAI,CAAS;IACb,IAAI,CAAU;IAEvB,YAAY,IAAY,EAAE,OAAe,EAAE,IAAc;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAClD,YAAY,OAAO,GAAG,uBAAuB;QAC5C,KAAK,CAAC,OAAO,CAAC,CAA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C,OAAgB;IACrD,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,CAAC;AACnH,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,OAAgB;IACjD,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,KAAK,KAAK,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9F,IAAI,QAAQ,IAAI,OAAO;QAAE,OAAO,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,CAAC;IACtD,IAAI,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACpE,OAAO,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC;AAC5F,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,KAAc;IACjD,IAAI,gBAAgB,CAAC,KAAK,CAAC,IAAI,qBAAqB,CAAC,KAAK,CAAC,IAAI,iBAAiB,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtG,MAAM,IAAI,QAAQ,CAAC,oBAAoB,CAAC,cAAc,EAAE,0BAA0B,CAAC,CAAC;AACrF,CAAC","sourcesContent":["export type JsonRpcId = string | number;\n\nexport interface JsonRpcRequest {\n\tjsonrpc: \"2.0\";\n\tid: JsonRpcId;\n\tmethod: string;\n\tparams?: unknown;\n}\n\nexport interface JsonRpcNotification {\n\tjsonrpc: \"2.0\";\n\tmethod: string;\n\tparams?: unknown;\n}\n\nexport interface JsonRpcErrorObject {\n\tcode: number;\n\tmessage: string;\n\tdata?: unknown;\n}\n\nexport interface JsonRpcSuccessResponse {\n\tjsonrpc: \"2.0\";\n\tid: JsonRpcId;\n\tresult: unknown;\n}\n\nexport interface JsonRpcErrorResponse {\n\tjsonrpc: \"2.0\";\n\tid: JsonRpcId;\n\terror: JsonRpcErrorObject;\n}\n\nexport type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;\n\nexport const JSON_RPC_ERROR_CODES = {\n\tparseError: -32700,\n\tinvalidRequest: -32600,\n\tmethodNotFound: -32601,\n\tinvalidParams: -32602,\n\tinternalError: -32603,\n} as const;\n\nexport class McpError extends Error {\n\treadonly code: number;\n\treadonly data: unknown;\n\n\tconstructor(code: number, message: string, data?: unknown) {\n\t\tsuper(message);\n\t\tthis.name = \"McpError\";\n\t\tthis.code = code;\n\t\tthis.data = data;\n\t}\n}\n\nexport class McpConnectionClosedError extends Error {\n\tconstructor(message = \"MCP connection closed\") {\n\t\tsuper(message);\n\t\tthis.name = \"McpConnectionClosedError\";\n\t}\n}\n\nexport class McpTimeoutError extends Error {\n\treadonly timeoutMs: number;\n\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`MCP request timed out after ${timeoutMs}ms`);\n\t\tthis.name = \"McpTimeoutError\";\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nexport class McpAbortError extends Error {\n\tconstructor(message = \"MCP request aborted\") {\n\t\tsuper(message);\n\t\tthis.name = \"AbortError\";\n\t}\n}\n\nexport function isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function toError(value: unknown): Error {\n\treturn value instanceof Error ? value : new Error(String(value));\n}\n\nexport function isJsonRpcId(value: unknown): value is JsonRpcId {\n\treturn typeof value === \"string\" || (typeof value === \"number\" && Number.isFinite(value));\n}\n\nexport function isJsonRpcRequest(message: unknown): message is JsonRpcRequest {\n\treturn (\n\t\tisObject(message) && message.jsonrpc === \"2.0\" && isJsonRpcId(message.id) && typeof message.method === \"string\"\n\t);\n}\n\nexport function isJsonRpcNotification(message: unknown): message is JsonRpcNotification {\n\treturn isObject(message) && message.jsonrpc === \"2.0\" && !(\"id\" in message) && typeof message.method === \"string\";\n}\n\nexport function isJsonRpcResponse(message: unknown): message is JsonRpcResponse {\n\tif (!isObject(message) || message.jsonrpc !== \"2.0\" || !isJsonRpcId(message.id)) return false;\n\tif (\"result\" in message) return !(\"error\" in message);\n\tif (!(\"error\" in message) || !isObject(message.error)) return false;\n\treturn typeof message.error.code === \"number\" && typeof message.error.message === \"string\";\n}\n\nexport function parseJsonRpcMessage(value: unknown): JsonRpcMessage {\n\tif (isJsonRpcRequest(value) || isJsonRpcNotification(value) || isJsonRpcResponse(value)) return value;\n\tthrow new McpError(JSON_RPC_ERROR_CODES.invalidRequest, \"Invalid JSON-RPC message\");\n}\n"]}