@opengeni/capabilities 0.3.3-canary.14 → 0.3.3-canary.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,3 +37,19 @@ Integration Definitions keep their existing local MCP adapters without
37
37
  claiming this descriptor. Google Drive remains one functional Integration row
38
38
  with its existing Connection and facet authority. See
39
39
  `docs/design/first-party-mcp-bridges.md`.
40
+
41
+ ## Curated Microsoft Graph schemas
42
+
43
+ Microsoft definitions explicitly use `provider_validated_json`: JSON request
44
+ bodies remain JSON values, and Graph validates their fields. Path/query/header
45
+ schemas, required bodies, media types, scopes, destinations and write approvals
46
+ are retained. Binary/text body schemas are retained. Optional response schemas
47
+ are omitted because the adapter returns an HTTP-result envelope. This avoids
48
+ expanding Graph's recursive entity graph into every operation. Custom OpenAPI
49
+ sources retain their full schema compilation. The mode participates in the
50
+ immutable revision digest; preview refuses revisions above the persistence bound.
51
+
52
+ Contacts uses delegated `People.Read` for `/me/people`. OneDrive uses
53
+ `Files.ReadWrite.All` and excludes the organization-only followed-sites API;
54
+ neither requires organization-wide people or SharePoint permissions merely to
55
+ connect a personal Microsoft account.
package/dist/http.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { IntegrationTransport, PinnedIntegrationTransportOptions } from "./
3
3
  export declare const DEFAULT_INTEGRATION_TIMEOUT_MS = 30000;
4
4
  export declare const DEFAULT_INTEGRATION_RESPONSE_BYTES: number;
5
5
  export declare const MAX_INTEGRATION_SPEC_BYTES: number;
6
+ export declare const MAX_CURATED_INTEGRATION_SPEC_BYTES: number;
6
7
  export declare const MAX_INTEGRATION_TOOLS = 2000;
7
8
  export declare function fetchIntegrationSourceDocument(transport: IntegrationTransport, sourceUrl: string, maxBytes?: number): Promise<Uint8Array>;
8
9
  export declare function createPinnedIntegrationTransport(options: PinnedIntegrationTransportOptions): IntegrationTransport;
package/dist/index.js CHANGED
@@ -176,6 +176,7 @@ import { pinnedFetch, readResponseBodyBounded } from "@opengeni/network";
176
176
  var DEFAULT_INTEGRATION_TIMEOUT_MS = 3e4;
177
177
  var DEFAULT_INTEGRATION_RESPONSE_BYTES = 4 * 1024 * 1024;
178
178
  var MAX_INTEGRATION_SPEC_BYTES = 8 * 1024 * 1024;
179
+ var MAX_CURATED_INTEGRATION_SPEC_BYTES = 64 * 1024 * 1024;
179
180
  var MAX_INTEGRATION_TOOLS = 2e3;
180
181
  async function fetchIntegrationSourceDocument(transport, sourceUrl, maxBytes = MAX_INTEGRATION_SPEC_BYTES) {
181
182
  const url = new URL(sourceUrl);
@@ -921,12 +922,18 @@ var forbiddenParameterHeaders = /* @__PURE__ */ new Set([
921
922
  "connection",
922
923
  "transfer-encoding"
923
924
  ]);
924
- function parseOpenApiDocument(source) {
925
+ function parseOpenApiDocument(source, options = {}) {
926
+ const maxBytes = options.maxBytes ?? MAX_INTEGRATION_SPEC_BYTES;
927
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_CURATED_INTEGRATION_SPEC_BYTES) {
928
+ throw new RangeError(
929
+ `OpenAPI parser limit must be between 1 and ${MAX_CURATED_INTEGRATION_SPEC_BYTES} bytes`
930
+ );
931
+ }
925
932
  const bytes = typeof source === "string" ? Buffer.byteLength(source) : source.byteLength;
926
- if (bytes === 0 || bytes > MAX_INTEGRATION_SPEC_BYTES) {
933
+ if (bytes === 0 || bytes > maxBytes) {
927
934
  throw new IntegrationProtocolError(
928
935
  "openapi_spec_size",
929
- `OpenAPI document must be between 1 and ${MAX_INTEGRATION_SPEC_BYTES} bytes`
936
+ `OpenAPI document must be between 1 and ${maxBytes} bytes`
930
937
  );
931
938
  }
932
939
  const text = typeof source === "string" ? source : new TextDecoder("utf-8", { fatal: true }).decode(source);
@@ -952,7 +959,9 @@ function parseOpenApiDocument(source) {
952
959
  }
953
960
  function compileOpenApiRevision(source, options) {
954
961
  const document = isRecord2(source) ? source : parseOpenApiDocument(source);
955
- const contentSha256 = sha256Hex(canonicalJson(document));
962
+ const contentSha256 = sha256Hex(
963
+ canonicalJson(options.schemaMode ? { document, schemaMode: options.schemaMode } : document)
964
+ );
956
965
  const revisionId = immutableRevisionId("openapi", contentSha256);
957
966
  const info = isRecord2(document.info) ? document.info : {};
958
967
  const documentServers = readServers(document.servers, options.baseUrl, options.sourceUrl);
@@ -976,7 +985,7 @@ function compileOpenApiRevision(source, options) {
976
985
  sharedParameters,
977
986
  readParameters(document, operation.parameters)
978
987
  );
979
- const requestBody = readRequestBody(document, operation.requestBody);
988
+ const requestBody = readRequestBody(document, operation.requestBody, options.schemaMode);
980
989
  const serverUrl = firstServerUrl(
981
990
  readServers(operation.servers, void 0, void 0),
982
991
  pathServers,
@@ -985,7 +994,7 @@ function compileOpenApiRevision(source, options) {
985
994
  const requiredScopeAlternatives = operation.security === void 0 ? documentSecurity : readSecurity(operation.security);
986
995
  const safety = classifyHttpSafety(method, operation);
987
996
  const inputSchema = operationInputSchema(parameters, requestBody);
988
- const outputSchema = operationOutputSchema(document, operation.responses);
997
+ const outputSchema = options.schemaMode ? void 0 : operationOutputSchema(document, operation.responses);
989
998
  const summary = stringValue(operation.summary) ?? stringValue(operation.description);
990
999
  tools.push({
991
1000
  id,
@@ -1294,14 +1303,18 @@ function mergeParameters(base, override) {
1294
1303
  for (const entry of override) merged.set(`${entry.location}:${entry.name}`, entry);
1295
1304
  return [...merged.values()];
1296
1305
  }
1297
- function readRequestBody(document, value) {
1306
+ function readRequestBody(document, value, schemaMode) {
1298
1307
  if (value === void 0) return void 0;
1299
1308
  const body = resolveObject(document, value, "request body");
1300
1309
  if (!isRecord2(body.content)) return void 0;
1301
1310
  const schemas = {};
1302
1311
  for (const [contentType, rawMedia] of Object.entries(body.content)) {
1303
1312
  if (!isRecord2(rawMedia)) continue;
1304
- schemas[contentType.toLowerCase()] = dereferenceSchema(document, rawMedia.schema);
1313
+ const normalizedType = contentType.toLowerCase();
1314
+ const jsonBody = normalizedType === "application/json" || normalizedType.endsWith("+json");
1315
+ schemas[normalizedType] = schemaMode === "provider_validated_json" && jsonBody ? {
1316
+ description: "Request JSON for this API operation. The provider validates fields; follow the operation documentation."
1317
+ } : dereferenceSchema(document, rawMedia.schema);
1305
1318
  }
1306
1319
  const contentTypes = Object.keys(schemas);
1307
1320
  return contentTypes.length === 0 ? void 0 : { required: body.required === true, contentTypes, schemas };
@@ -1671,6 +1684,7 @@ var MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION = {
1671
1684
  source: {
1672
1685
  kind: "openapi",
1673
1686
  url: MICROSOFT_GRAPH_OPENAPI_URL,
1687
+ schemaMode: "provider_validated_json",
1674
1688
  operationPathPrefixes: [
1675
1689
  "/me/messages",
1676
1690
  "/me/mailFolders",
@@ -1694,6 +1708,7 @@ var MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION = {
1694
1708
  source: {
1695
1709
  kind: "openapi",
1696
1710
  url: MICROSOFT_GRAPH_OPENAPI_URL,
1711
+ schemaMode: "provider_validated_json",
1697
1712
  operationPathPrefixes: [
1698
1713
  "/me/calendar",
1699
1714
  "/me/calendars",
@@ -1753,10 +1768,11 @@ var MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION = {
1753
1768
  source: {
1754
1769
  kind: "openapi",
1755
1770
  url: MICROSOFT_GRAPH_OPENAPI_URL,
1771
+ schemaMode: "provider_validated_json",
1756
1772
  operationPathPrefixes: ["/me/contacts", "/me/contactFolders", "/me/people"]
1757
1773
  },
1758
1774
  baseUrl: MICROSOFT_GRAPH_BASE_URL,
1759
- authentication: microsoftOAuth(["Contacts.ReadWrite", "People.Read.All"]),
1775
+ authentication: microsoftOAuth(["Contacts.ReadWrite", "People.Read"]),
1760
1776
  facets: [accountIdentityFacet("microsoft")]
1761
1777
  };
1762
1778
  var MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION = {
@@ -1768,10 +1784,13 @@ var MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION = {
1768
1784
  source: {
1769
1785
  kind: "openapi",
1770
1786
  url: MICROSOFT_GRAPH_OPENAPI_URL,
1771
- operationPathPrefixes: ["/me/drive", "/me/drives", "/me/followedSites", "/drives", "/shares"]
1787
+ schemaMode: "provider_validated_json",
1788
+ operationPathPrefixes: ["/me/drive", "/me/drives", "/drives", "/shares"],
1789
+ // Excel's nested workbook API is a separate surface, not file management.
1790
+ excludedOperationPathPrefixes: ["/drives/{drive-id}/items/{driveItem-id}/workbook"]
1772
1791
  },
1773
1792
  baseUrl: MICROSOFT_GRAPH_BASE_URL,
1774
- authentication: microsoftOAuth(["Files.ReadWrite.All", "Sites.ReadWrite.All"]),
1793
+ authentication: microsoftOAuth(["Files.ReadWrite.All"]),
1775
1794
  facets: [driveKnowledgeFacet("microsoft-onedrive"), accountIdentityFacet("microsoft")]
1776
1795
  };
1777
1796
  var CORE_INTEGRATION_DEFINITIONS = [
@@ -1795,12 +1814,15 @@ function filterOpenApiDocumentForDefinition(document, definition) {
1795
1814
  return document;
1796
1815
  }
1797
1816
  const operationPathPrefixes = definition.source.operationPathPrefixes;
1817
+ const excludedOperationPathPrefixes = definition.source.excludedOperationPathPrefixes ?? [];
1798
1818
  if (!isRecord3(document.paths)) {
1799
1819
  throw new IntegrationProtocolError("openapi_paths", "OpenAPI document has no paths object");
1800
1820
  }
1801
1821
  const paths = Object.fromEntries(
1802
1822
  Object.entries(document.paths).filter(
1803
- ([path]) => operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`))
1823
+ ([path]) => operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)) && !excludedOperationPathPrefixes.some(
1824
+ (prefix) => path === prefix || path.startsWith(`${prefix}/`)
1825
+ )
1804
1826
  )
1805
1827
  );
1806
1828
  if (Object.keys(paths).length === 0) {
@@ -2151,6 +2173,7 @@ export {
2151
2173
  IntegrationInvocationError,
2152
2174
  IntegrationProtocolError,
2153
2175
  LOCAL_MCP_BRIDGE_CONTRACT_VERSION,
2176
+ MAX_CURATED_INTEGRATION_SPEC_BYTES,
2154
2177
  MAX_INTEGRATION_SPEC_BYTES,
2155
2178
  MAX_INTEGRATION_TOOLS,
2156
2179
  MICROSOFT_GRAPH_BASE_URL,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/auth.ts","../src/graphql.ts","../src/http.ts","../src/revision.ts","../src/mcp-manifest.ts","../src/mcp-bridge.ts","../src/openapi.ts","../src/integration-definitions.ts","../src/integration-presentations.ts"],"sourcesContent":["import type { FetchLike, OutboundNetworkSettings } from \"@opengeni/network\";\n\nexport type IntegrationProtocol = \"mcp\" | \"openapi\" | \"graphql\";\nexport type IntegrationToolSafety = \"read\" | \"write\" | \"destructive\";\nexport type IntegrationApprovalMode = \"never\" | \"ask\";\n\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\nexport interface IntegrationToolDefinition {\n readonly id: string;\n readonly operationKey: string;\n readonly name: string;\n readonly description: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly safety: IntegrationToolSafety;\n readonly approvalMode: IntegrationApprovalMode;\n readonly deprecated: boolean;\n}\n\nexport type CredentialCarrier = \"header\" | \"query\" | \"cookie\";\n\nexport interface IntegrationCredentialPlacement {\n readonly carrier: CredentialCarrier;\n readonly name: string;\n readonly value: string;\n readonly prefix?: string;\n}\n\nexport interface IntegrationCredentialAudience {\n /** Exact normalized origin the credential may reach. */\n readonly origin: string;\n /** Optional normalized path prefix. Defaults to `/`. */\n readonly pathPrefix?: string;\n}\n\nexport interface ResolvedIntegrationCredential {\n readonly audience: IntegrationCredentialAudience;\n readonly placements: readonly IntegrationCredentialPlacement[];\n /** Exact accepted-attempt fence invoked immediately before one HTTP request. */\n readonly authorizeProviderRequest?: () => Promise<boolean>;\n readonly expiresAt?: string;\n readonly scope?: readonly string[];\n}\n\nexport interface IntegrationInvocationAuthority {\n readonly accountId: string;\n readonly workspaceId: string;\n readonly sessionId?: string;\n readonly rootSessionId?: string;\n readonly turnId?: string;\n readonly attemptId?: string;\n readonly initiatingSubjectId?: string;\n readonly connectionRef?: string;\n}\n\nexport interface ResolveIntegrationCredentialRequest extends IntegrationInvocationAuthority {\n readonly protocol: Exclude<IntegrationProtocol, \"mcp\">;\n readonly definitionId: string;\n readonly revisionId: string;\n readonly operationKey: string;\n readonly destinationUrl: string;\n readonly requiredScopeAlternatives?: readonly (readonly string[])[];\n /** Refresh the exact bound Connection for a safe retry or a later call. */\n readonly forceRefresh?: boolean;\n}\n\nexport interface IntegrationCredentialResolver {\n resolve(\n request: ResolveIntegrationCredentialRequest,\n ): Promise<ResolvedIntegrationCredential | null>;\n}\n\nexport interface IntegrationTransport {\n readonly fetch: FetchLike;\n}\n\nexport interface PinnedIntegrationTransportOptions {\n readonly network: OutboundNetworkSettings;\n readonly fetchImpl?: FetchLike;\n}\n\nexport type IntegrationRevisionSource = {\n readonly url?: string;\n readonly provider?: string;\n readonly fetchedAt?: string;\n};\n\nexport interface IntegrationRevision<\n TBinding = unknown,\n TProtocol extends Exclude<IntegrationProtocol, \"mcp\"> = Exclude<IntegrationProtocol, \"mcp\">,\n> {\n readonly id: string;\n readonly protocol: TProtocol;\n readonly definitionId: string;\n readonly contentSha256: string;\n readonly source: IntegrationRevisionSource;\n readonly title: string;\n readonly description?: string;\n readonly version?: string;\n readonly tools: readonly IntegrationToolDefinition[];\n readonly bindings: Readonly<Record<string, TBinding>>;\n}\n\nexport type InvocationOutcome = \"not_started\" | \"unknown\" | \"failed\";\n\nexport class IntegrationProtocolError extends Error {\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"IntegrationProtocolError\";\n }\n}\n\nexport class IntegrationInvocationError extends Error {\n constructor(\n readonly code: string,\n message: string,\n readonly outcome: InvocationOutcome,\n readonly retryable: boolean,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"IntegrationInvocationError\";\n }\n}\n","import type { IntegrationCredentialPlacement, ResolvedIntegrationCredential } from \"./types\";\nimport { IntegrationInvocationError } from \"./types\";\n\nconst forbiddenCredentialHeaders = new Set([\n \"connection\",\n \"content-length\",\n \"host\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\nconst MAX_CREDENTIAL_PLACEMENTS = 32;\nconst MAX_CREDENTIAL_NAME_LENGTH = 256;\nconst MAX_CREDENTIAL_VALUE_LENGTH = 16_384;\nconst headerNamePattern = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;\nconst queryNamePattern = /^[A-Za-z0-9._~-]+$/;\nconst cookieNamePattern = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nfunction normalizeAudiencePath(path: string | undefined): string {\n if (!path?.trim()) return \"/\";\n const normalized = path.startsWith(\"/\") ? path : `/${path}`;\n return normalized.endsWith(\"/\") ? normalized : `${normalized}/`;\n}\n\nexport function assertCredentialAudience(\n credential: ResolvedIntegrationCredential,\n destination: URL,\n): void {\n let audience: URL;\n try {\n audience = new URL(credential.audience.origin);\n } catch {\n throw new IntegrationInvocationError(\n \"credential_audience_invalid\",\n \"Connection credential audience is invalid\",\n \"not_started\",\n false,\n );\n }\n if (\n audience.origin !== destination.origin ||\n audience.username ||\n audience.password ||\n audience.pathname !== \"/\" ||\n audience.search ||\n audience.hash\n ) {\n throw new IntegrationInvocationError(\n \"credential_audience_mismatch\",\n \"Connection credential is not authorized for this integration destination\",\n \"not_started\",\n false,\n );\n }\n const prefix = normalizeAudiencePath(credential.audience.pathPrefix);\n const path = destination.pathname.endsWith(\"/\")\n ? destination.pathname\n : `${destination.pathname}/`;\n if (!path.startsWith(prefix)) {\n throw new IntegrationInvocationError(\n \"credential_path_mismatch\",\n \"Connection credential is not authorized for this integration path\",\n \"not_started\",\n false,\n );\n }\n}\n\nfunction placementValue(placement: IntegrationCredentialPlacement): string {\n return `${placement.prefix ?? \"\"}${placement.value}`;\n}\n\nfunction validateCredentialPlacements(placements: readonly IntegrationCredentialPlacement[]): void {\n if (placements.length === 0 || placements.length > MAX_CREDENTIAL_PLACEMENTS) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placement count is invalid\",\n \"not_started\",\n false,\n );\n }\n const seen = new Set<string>();\n for (const placement of placements) {\n const name = placement.name;\n const value = placementValue(placement);\n const normalizedName = placement.carrier === \"header\" ? name.toLowerCase() : name;\n if (\n name.length === 0 ||\n name.length > MAX_CREDENTIAL_NAME_LENGTH ||\n placement.value.length === 0 ||\n value.length > MAX_CREDENTIAL_VALUE_LENGTH ||\n /[\\r\\n\\0]/.test(name) ||\n /[\\r\\n\\0]/.test(value)\n ) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placement is invalid\",\n \"not_started\",\n false,\n );\n }\n if (placement.carrier === \"header\") {\n if (\n !headerNamePattern.test(name) ||\n forbiddenCredentialHeaders.has(normalizedName) ||\n normalizedName.startsWith(\"sec-\")\n ) {\n throw new IntegrationInvocationError(\n \"credential_header_forbidden\",\n \"Connection credential targets a forbidden request header\",\n \"not_started\",\n false,\n );\n }\n } else if (placement.carrier === \"query\") {\n if (!queryNamePattern.test(name)) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential query placement is invalid\",\n \"not_started\",\n false,\n );\n }\n } else if (!cookieNamePattern.test(name) || /;/.test(value)) {\n throw new IntegrationInvocationError(\n \"credential_cookie_invalid\",\n \"Connection credential cookie placement is invalid\",\n \"not_started\",\n false,\n );\n }\n const key = `${placement.carrier}\\0${normalizedName}`;\n if (seen.has(key)) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placements contain a duplicate destination\",\n \"not_started\",\n false,\n );\n }\n seen.add(key);\n }\n}\n\nexport function applyCredentialPlacements(\n destination: URL,\n headers: Headers,\n credential: ResolvedIntegrationCredential,\n): void {\n assertCredentialAudience(credential, destination);\n validateCredentialPlacements(credential.placements);\n const cookies: string[] = [];\n for (const placement of credential.placements) {\n const name = placement.name;\n const value = placementValue(placement);\n if (placement.carrier === \"header\") {\n headers.set(name, value);\n } else if (placement.carrier === \"query\") {\n destination.searchParams.set(name, value);\n } else {\n cookies.push(`${name}=${value}`);\n }\n }\n if (cookies.length > 0) {\n const current = headers.get(\"cookie\");\n headers.set(\"cookie\", [...(current ? [current] : []), ...cookies].join(\"; \"));\n }\n}\n","import type { CallToolResultContent, MCPCallToolOptions, MCPServer } from \"@openai/agents\";\nimport {\n buildClientSchema,\n getIntrospectionQuery,\n getNamedType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n parse,\n type GraphQLInputType,\n type GraphQLNamedType,\n type GraphQLOutputType,\n type IntrospectionQuery,\n} from \"graphql\";\n\nimport { applyCredentialPlacements } from \"./auth\";\nimport {\n DEFAULT_INTEGRATION_RESPONSE_BYTES,\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n MAX_INTEGRATION_SPEC_BYTES,\n MAX_INTEGRATION_TOOLS,\n fetchWithDeadline,\n readIntegrationResponse,\n} from \"./http\";\nimport { canonicalJson, immutableRevisionId, sha256Hex, stableToolId } from \"./revision\";\nimport type {\n IntegrationCredentialResolver,\n IntegrationInvocationAuthority,\n IntegrationRevision,\n IntegrationTransport,\n JsonSchema,\n} from \"./types\";\nimport { IntegrationInvocationError, IntegrationProtocolError } from \"./types\";\n\nexport interface GraphqlOperationBinding {\n readonly kind: \"query\" | \"mutation\";\n readonly fieldName: string;\n readonly operationName: string;\n readonly variableDefinitions: readonly string[];\n readonly variableNames: readonly string[];\n readonly defaultSelection?: string;\n readonly selectionAllowed: boolean;\n}\n\nexport type GraphqlRevision = IntegrationRevision<GraphqlOperationBinding, \"graphql\">;\n\nexport interface CompileGraphqlOptions {\n readonly definitionId: string;\n readonly endpoint: string;\n readonly name?: string;\n readonly sourceUrl?: string;\n readonly provider?: string;\n}\n\nexport interface GraphqlServerOptions {\n readonly revision: GraphqlRevision;\n readonly endpoint: string;\n readonly transport: IntegrationTransport;\n readonly credentialResolver?: IntegrationCredentialResolver;\n readonly authority: IntegrationInvocationAuthority;\n readonly staticHeaders?: Readonly<Record<string, string>>;\n readonly staticQuery?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly maxResponseBytes?: number;\n}\n\ntype LocalMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\nexport function compileGraphqlRevision(\n introspection: IntrospectionQuery | { readonly data?: IntrospectionQuery } | string,\n options: CompileGraphqlOptions,\n): GraphqlRevision {\n const document = parseIntrospection(introspection);\n let schema;\n try {\n schema = buildClientSchema(document);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_introspection_invalid\",\n \"GraphQL introspection result cannot build a client schema\",\n );\n }\n const endpoint = validateGraphqlEndpoint(options.endpoint);\n const contentSha256 = sha256Hex(canonicalJson(document));\n const id = immutableRevisionId(\"graphql\", contentSha256);\n const tools = [] as GraphqlRevision[\"tools\"] extends readonly (infer T)[] ? T[] : never;\n const bindings: Record<string, GraphqlOperationBinding> = {};\n const seen = new Map<string, number>();\n\n for (const [kind, root] of [\n [\"query\", schema.getQueryType()],\n [\"mutation\", schema.getMutationType()],\n ] as const) {\n if (!root) continue;\n for (const field of Object.values(root.getFields()).sort((left, right) =>\n left.name.localeCompare(right.name),\n )) {\n const toolId = stableToolId(`${kind}_${field.name}`, seen);\n const namedOutput = getNamedType(field.type);\n const selectionAllowed = !isLeafType(namedOutput);\n const defaultSelection = selectionAllowed\n ? buildDefaultSelection(field.type, new Set(), 0)\n : undefined;\n const properties: Record<string, unknown> = Object.fromEntries(\n field.args.map((arg) => [\n arg.name,\n {\n ...inputTypeSchema(arg.type, new Set(), 0),\n ...(arg.description ? { description: arg.description } : {}),\n },\n ]),\n );\n if (selectionAllowed) {\n properties.select = {\n type: \"string\",\n description:\n \"Optional GraphQL field selection without outer braces. The default selects safe scalar fields.\",\n maxLength: 4_000,\n };\n }\n const required = field.args.filter((arg) => isNonNullType(arg.type)).map((arg) => arg.name);\n const description = [\n field.description?.trim(),\n kind === \"mutation\"\n ? \"Changes external state and requires approval.\"\n : \"Read-only GraphQL query.\",\n ]\n .filter(Boolean)\n .join(\" \");\n tools.push({\n id: toolId,\n operationKey: `${kind}:${field.name}`,\n name: field.name,\n description,\n inputSchema: {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n },\n safety: kind === \"query\" ? \"read\" : \"write\",\n approvalMode: kind === \"query\" ? \"never\" : \"ask\",\n deprecated: field.deprecationReason != null,\n });\n bindings[toolId] = {\n kind,\n fieldName: field.name,\n operationName: stableGraphqlName(`${kind}_${field.name}`),\n variableDefinitions: field.args.map((arg) => `$${arg.name}: ${String(arg.type)}`),\n variableNames: field.args.map((arg) => arg.name),\n ...(defaultSelection ? { defaultSelection } : {}),\n selectionAllowed,\n };\n if (tools.length > MAX_INTEGRATION_TOOLS) {\n throw new IntegrationProtocolError(\n \"graphql_tool_limit\",\n `GraphQL schema exceeds the ${MAX_INTEGRATION_TOOLS}-tool limit`,\n );\n }\n }\n }\n if (tools.length === 0) {\n throw new IntegrationProtocolError(\"graphql_empty\", \"GraphQL schema exposes no root fields\");\n }\n return {\n id,\n protocol: \"graphql\",\n definitionId: options.definitionId,\n contentSha256,\n source: {\n url: options.sourceUrl ?? endpoint,\n ...(options.provider ? { provider: options.provider } : {}),\n },\n title: options.name?.trim() || options.definitionId,\n tools,\n bindings,\n };\n}\n\nexport async function fetchGraphqlIntrospection(\n options: Omit<GraphqlServerOptions, \"revision\">,\n): Promise<IntrospectionQuery> {\n const request = { query: getIntrospectionQuery({ descriptions: true }) };\n const firstCredential = await resolveGraphqlCredential(\n options,\n \"graphql-introspection\",\n \"pending\",\n \"__introspection\",\n false,\n );\n let response = await sendGraphqlRequest(options, request, firstCredential);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveGraphqlCredential(\n options,\n \"graphql-introspection\",\n \"pending\",\n \"__introspection\",\n true,\n );\n await response.body?.cancel().catch(() => undefined);\n if (!refreshed) {\n throw new IntegrationInvocationError(\n \"graphql_introspection_rejected\",\n \"GraphQL endpoint did not return an introspection schema\",\n \"failed\",\n false,\n 401,\n );\n }\n response = await sendGraphqlRequest(options, request, refreshed);\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"GraphQL endpoint attempted to redirect the introspection request\",\n \"unknown\",\n false,\n response.status,\n );\n }\n const body = await readIntegrationResponse(response, MAX_INTEGRATION_SPEC_BYTES);\n if (!response.ok || !isRecord(body.data) || !isRecord(body.data.data)) {\n throw new IntegrationInvocationError(\n \"graphql_introspection_rejected\",\n \"GraphQL endpoint did not return an introspection schema\",\n \"failed\",\n false,\n response.status,\n );\n }\n return body.data.data as unknown as IntrospectionQuery;\n}\n\nexport class GraphqlMcpServer implements MCPServer {\n readonly cacheToolsList = true;\n readonly useStructuredContent = true;\n readonly name: string;\n\n constructor(private readonly options: GraphqlServerOptions) {\n this.name = `graphql:${stableToolId(options.revision.definitionId)}`;\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n async invalidateToolsCache(): Promise<void> {}\n\n async listTools(): Promise<LocalMcpTool[]> {\n return this.options.revision.tools.map(\n (tool) =>\n ({\n name: tool.id,\n description: tool.description,\n inputSchema: normalizeMcpSchema(tool.inputSchema),\n annotations: {\n readOnlyHint: tool.safety === \"read\",\n destructiveHint: false,\n idempotentHint: tool.safety === \"read\",\n openWorldHint: true,\n },\n _meta: {\n \"opengeni/approvalMode\": tool.approvalMode,\n \"opengeni/operationKey\": tool.operationKey,\n \"opengeni/revisionId\": this.options.revision.id,\n },\n }) as LocalMcpTool,\n );\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n _meta?: Record<string, unknown> | null,\n callOptions?: MCPCallToolOptions,\n ): Promise<CallToolResultContent> {\n const result = await invokeGraphqlOperation(\n this.options,\n toolName,\n args ?? {},\n callOptions?.signal,\n );\n const content = [\n { type: \"text\" as const, text: JSON.stringify(result) },\n ] as CallToolResultContent;\n content.structuredContent = result;\n content.isError = result.ok === false;\n return content;\n }\n}\n\nexport function createGraphqlMcpServer(options: GraphqlServerOptions): MCPServer {\n return new GraphqlMcpServer(options);\n}\n\nexport async function invokeGraphqlOperation(\n options: GraphqlServerOptions,\n toolId: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const binding = options.revision.bindings[toolId];\n if (!binding) {\n throw new IntegrationInvocationError(\n \"operation_not_found\",\n \"GraphQL operation is not present in the frozen revision\",\n \"not_started\",\n false,\n );\n }\n const select = binding.selectionAllowed\n ? validateGraphqlSelection(\n typeof args.select === \"string\" ? args.select : (binding.defaultSelection ?? \"__typename\"),\n )\n : undefined;\n const variables = Object.fromEntries(\n binding.variableNames.flatMap((name) => (args[name] === undefined ? [] : [[name, args[name]]])),\n );\n const definitions = binding.variableDefinitions.length\n ? `(${binding.variableDefinitions.join(\", \")})`\n : \"\";\n const argumentsText = binding.variableNames.length\n ? `(${binding.variableNames.map((name) => `${name}: $${name}`).join(\", \")})`\n : \"\";\n const query = `${binding.kind} ${binding.operationName}${definitions} { ${binding.fieldName}${argumentsText}${select ? ` { ${select} }` : \"\"} }`;\n const request = { query, variables, operationName: binding.operationName };\n const firstCredential = await resolveGraphqlCredential(\n options,\n options.revision.definitionId,\n options.revision.id,\n toolId,\n false,\n );\n let response = await sendGraphqlRequest(options, request, firstCredential, signal);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveGraphqlCredential(\n options,\n options.revision.definitionId,\n options.revision.id,\n toolId,\n true,\n );\n await response.body?.cancel().catch(() => undefined);\n if (binding.kind === \"query\" && refreshed) {\n response = await sendGraphqlRequest(options, request, refreshed, signal);\n } else {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this GraphQL operation\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n 401,\n );\n }\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"GraphQL endpoint attempted to redirect a credential-bearing request\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n response.status,\n );\n }\n const payload = await readIntegrationResponse(\n response,\n options.maxResponseBytes ?? DEFAULT_INTEGRATION_RESPONSE_BYTES,\n );\n if (response.status === 401 || response.status === 403) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this GraphQL operation\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n response.status,\n );\n }\n const graph = isRecord(payload.data) ? payload.data : {};\n return {\n ok: response.ok && !Array.isArray(graph.errors),\n status: response.status,\n data: graph.data ?? null,\n errors: graph.errors ?? null,\n };\n}\n\nasync function resolveGraphqlCredential(\n options: Omit<GraphqlServerOptions, \"revision\"> | GraphqlServerOptions,\n definitionId: string,\n revisionId: string,\n operationKey: string,\n forceRefresh: boolean,\n): Promise<Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>> {\n if (!options.credentialResolver || !options.authority.connectionRef) return null;\n const credential = await options.credentialResolver.resolve({\n ...options.authority,\n protocol: \"graphql\",\n definitionId,\n revisionId,\n operationKey,\n destinationUrl: graphqlEndpoint(options).toString(),\n ...(forceRefresh ? { forceRefresh: true } : {}),\n });\n if (!credential && !forceRefresh) {\n throw new IntegrationInvocationError(\n \"connection_required\",\n \"This GraphQL integration needs a connected account\",\n \"not_started\",\n false,\n );\n }\n return credential;\n}\n\nasync function sendGraphqlRequest(\n options: Omit<GraphqlServerOptions, \"revision\"> | GraphqlServerOptions,\n request: Record<string, unknown>,\n credential: Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>,\n signal?: AbortSignal,\n): Promise<Response> {\n const endpoint = graphqlEndpoint(options);\n const headers = new Headers(options.staticHeaders);\n headers.set(\"accept\", \"application/json\");\n headers.set(\"content-type\", \"application/json\");\n if (credential) applyCredentialPlacements(endpoint, headers, credential);\n if (credential?.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await credential.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n \"not_started\",\n false,\n );\n }\n }\n return await fetchWithDeadline(\n options.transport,\n endpoint,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(request),\n ...(signal ? { signal } : {}),\n },\n options.timeoutMs ?? DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n}\n\nfunction graphqlEndpoint(options: Pick<GraphqlServerOptions, \"endpoint\" | \"staticQuery\">): URL {\n const endpoint = new URL(validateGraphqlEndpoint(options.endpoint));\n for (const [name, value] of Object.entries(options.staticQuery ?? {})) {\n endpoint.searchParams.set(name, value);\n }\n return endpoint;\n}\n\nexport function validateGraphqlSelection(value: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.length > 4_000) {\n throw new IntegrationInvocationError(\n \"graphql_selection_invalid\",\n \"GraphQL selection must contain between 1 and 4000 characters\",\n \"not_started\",\n false,\n );\n }\n try {\n const document = parse(`fragment OpenGeniSelection on Placeholder { ${normalized} }`);\n if (\n document.definitions.length !== 1 ||\n document.definitions[0]?.kind !== \"FragmentDefinition\"\n ) {\n throw new Error(\"invalid selection document\");\n }\n return normalized;\n } catch {\n throw new IntegrationInvocationError(\n \"graphql_selection_invalid\",\n \"GraphQL selection is invalid\",\n \"not_started\",\n false,\n );\n }\n}\n\nfunction parseIntrospection(\n value: IntrospectionQuery | { readonly data?: IntrospectionQuery } | string,\n): IntrospectionQuery {\n let parsed: unknown = value;\n if (typeof value === \"string\") {\n if (Buffer.byteLength(value) > MAX_INTEGRATION_SPEC_BYTES) {\n throw new IntegrationProtocolError(\n \"graphql_introspection_size\",\n `GraphQL introspection exceeds ${MAX_INTEGRATION_SPEC_BYTES} bytes`,\n );\n }\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_introspection_parse\",\n \"GraphQL introspection is not valid JSON\",\n );\n }\n }\n if (isRecord(parsed) && isRecord(parsed.data) && isRecord(parsed.data.__schema)) {\n return parsed.data as unknown as IntrospectionQuery;\n }\n if (isRecord(parsed) && isRecord(parsed.__schema)) {\n return parsed as unknown as IntrospectionQuery;\n }\n throw new IntegrationProtocolError(\n \"graphql_introspection_shape\",\n \"GraphQL introspection result has no __schema object\",\n );\n}\n\nfunction validateGraphqlEndpoint(value: string): string {\n let endpoint: URL;\n try {\n endpoint = new URL(value);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_endpoint_invalid\",\n \"GraphQL endpoint URL is invalid\",\n );\n }\n if (\n !/^https?:$/.test(endpoint.protocol) ||\n endpoint.username ||\n endpoint.password ||\n endpoint.hash\n ) {\n throw new IntegrationProtocolError(\n \"graphql_endpoint_invalid\",\n \"GraphQL endpoint URL is invalid\",\n );\n }\n return endpoint.toString();\n}\n\nfunction inputTypeSchema(input: GraphQLInputType, seen: Set<string>, depth: number): JsonSchema {\n if (depth > 12) return {};\n if (isNonNullType(input)) return inputTypeSchema(input.ofType, seen, depth + 1);\n if (isListType(input)) {\n return { type: \"array\", items: inputTypeSchema(input.ofType, seen, depth + 1) };\n }\n const type = getNamedType(input);\n if (isScalarType(type)) return scalarSchema(type.name);\n if (isEnumType(type))\n return { type: \"string\", enum: type.getValues().map((entry) => entry.name) };\n if (isInputObjectType(type)) {\n if (seen.has(type.name)) return { type: \"object\", additionalProperties: true };\n const nextSeen = new Set(seen).add(type.name);\n const fields = Object.values(type.getFields());\n return {\n type: \"object\",\n properties: Object.fromEntries(\n fields.map((field) => [\n field.name,\n {\n ...inputTypeSchema(field.type, nextSeen, depth + 1),\n ...(field.description ? { description: field.description } : {}),\n },\n ]),\n ),\n required: fields.filter((field) => isNonNullType(field.type)).map((field) => field.name),\n additionalProperties: false,\n };\n }\n return {};\n}\n\nfunction scalarSchema(name: string): JsonSchema {\n if (name === \"Boolean\") return { type: \"boolean\" };\n if (name === \"Int\") return { type: \"integer\" };\n if (name === \"Float\") return { type: \"number\" };\n if (name === \"ID\" || name === \"String\") return { type: \"string\" };\n return { description: `GraphQL scalar ${name}` };\n}\n\nfunction buildDefaultSelection(\n output: GraphQLOutputType,\n seen: Set<string>,\n depth: number,\n): string | undefined {\n const type = getNamedType(output);\n if (isLeafType(type)) return undefined;\n if (depth > 2 || seen.has(type.name)) return \"__typename\";\n if (isUnionType(type) || isInterfaceType(type)) return \"__typename\";\n if (!isObjectType(type)) return \"__typename\";\n const nextSeen = new Set(seen).add(type.name);\n const fields = Object.values(type.getFields());\n const scalarFields = fields.filter((field) => isLeafType(getNamedType(field.type))).slice(0, 20);\n const selections = scalarFields.map((field) => field.name);\n if (selections.length < 3 && depth < 2) {\n const nested = fields.find(\n (field) => field.args.length === 0 && !isLeafType(getNamedType(field.type)),\n );\n if (nested) {\n const child = buildDefaultSelection(nested.type, nextSeen, depth + 1);\n if (child) selections.push(`${nested.name} { ${child} }`);\n }\n }\n return selections.length ? selections.join(\" \") : \"__typename\";\n}\n\nfunction isLeafType(type: GraphQLNamedType): boolean {\n return isScalarType(type) || isEnumType(type);\n}\n\nfunction stableGraphqlName(value: string): string {\n const normalized = value.replace(/[^_0-9A-Za-z]/g, \"_\").replace(/^([^_A-Za-z])/, \"_$1\");\n return normalized || \"OpenGeniOperation\";\n}\n\nfunction normalizeMcpSchema(schema: JsonSchema): LocalMcpTool[\"inputSchema\"] {\n return {\n type: \"object\",\n properties: isRecord(schema.properties) ? schema.properties : {},\n required: Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [],\n additionalProperties: schema.additionalProperties === true,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { pinnedFetch, readResponseBodyBounded, type FetchLike } from \"@opengeni/network\";\n\nimport type { IntegrationTransport, PinnedIntegrationTransportOptions } from \"./types\";\nimport { IntegrationInvocationError } from \"./types\";\n\nexport const DEFAULT_INTEGRATION_TIMEOUT_MS = 30_000;\nexport const DEFAULT_INTEGRATION_RESPONSE_BYTES = 4 * 1024 * 1024;\nexport const MAX_INTEGRATION_SPEC_BYTES = 8 * 1024 * 1024;\nexport const MAX_INTEGRATION_TOOLS = 2_000;\n\nexport async function fetchIntegrationSourceDocument(\n transport: IntegrationTransport,\n sourceUrl: string,\n maxBytes = MAX_INTEGRATION_SPEC_BYTES,\n): Promise<Uint8Array> {\n const url = new URL(sourceUrl);\n const response = await fetchWithDeadline(\n transport,\n url,\n {\n method: \"GET\",\n headers: { accept: \"application/json, application/yaml, text/yaml, */*;q=0.5\" },\n },\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"source_redirect_rejected\",\n \"Integration source attempted to redirect\",\n \"failed\",\n false,\n response.status,\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"source_fetch_rejected\",\n \"Integration source could not be read\",\n \"failed\",\n response.status >= 500,\n response.status,\n );\n }\n return await readResponseBodyBounded(response, maxBytes, \"Integration source\");\n}\n\nexport function createPinnedIntegrationTransport(\n options: PinnedIntegrationTransportOptions,\n): IntegrationTransport {\n return {\n fetch: (input, init) =>\n pinnedFetch(input, init, options.network, {\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n label: \"Integration request\",\n requireHttpsOutsideLocalTest: true,\n }),\n };\n}\n\nexport function directIntegrationTransport(fetchImpl: FetchLike): IntegrationTransport {\n return { fetch: fetchImpl };\n}\n\nexport async function fetchWithDeadline(\n transport: IntegrationTransport,\n url: URL,\n init: RequestInit,\n timeoutMs = DEFAULT_INTEGRATION_TIMEOUT_MS,\n): Promise<Response> {\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) {\n throw new RangeError(\"integration timeout must be between 1 and 120000 milliseconds\");\n }\n const controller = new AbortController();\n const onAbort = () => controller.abort(init.signal?.reason);\n if (init.signal?.aborted) onAbort();\n else init.signal?.addEventListener(\"abort\", onAbort, { once: true });\n const timer = setTimeout(\n () => controller.abort(new Error(\"integration request timed out\")),\n timeoutMs,\n );\n try {\n return await transport.fetch(url, {\n ...init,\n signal: controller.signal,\n redirect: \"manual\",\n });\n } catch {\n const timedOut = controller.signal.aborted && !init.signal?.aborted;\n throw new IntegrationInvocationError(\n timedOut ? \"request_timeout\" : \"request_failed\",\n timedOut ? \"Integration request timed out\" : \"Integration request failed\",\n requestCouldHaveStarted(init.method) ? \"unknown\" : \"not_started\",\n !requestCouldHaveStarted(init.method),\n );\n } finally {\n clearTimeout(timer);\n init.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction requestCouldHaveStarted(method: string | undefined): boolean {\n const normalized = (method ?? \"GET\").toUpperCase();\n return normalized !== \"GET\" && normalized !== \"HEAD\" && normalized !== \"OPTIONS\";\n}\n\nexport async function readIntegrationResponse(\n response: Response,\n maxBytes = DEFAULT_INTEGRATION_RESPONSE_BYTES,\n): Promise<{ data: unknown; contentType: string; bytes: number }> {\n const body = await readResponseBodyBounded(response, maxBytes, \"Integration response\");\n const contentType =\n response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase() ?? \"\";\n if (body.byteLength === 0) return { data: null, contentType, bytes: 0 };\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(body);\n if (contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n try {\n return { data: JSON.parse(text), contentType, bytes: body.byteLength };\n } catch {\n throw new IntegrationInvocationError(\n \"response_json_invalid\",\n \"Integration returned invalid JSON\",\n \"failed\",\n false,\n response.status,\n );\n }\n }\n return { data: text, contentType, bytes: body.byteLength };\n}\n","import { createHash } from \"node:crypto\";\n\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, canonicalize(entry)]),\n );\n}\n\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(canonicalize(value));\n}\n\nexport function sha256Hex(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function immutableRevisionId(protocol: string, contentSha256: string): string {\n if (!/^[a-f0-9]{64}$/.test(contentSha256)) {\n throw new Error(\"contentSha256 must be a lowercase SHA-256 digest\");\n }\n return `${protocol}:${contentSha256.slice(0, 24)}`;\n}\n\nexport function stableToolId(value: string, seen?: Map<string, number>): string {\n const normalized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, 54);\n const base = normalized || \"tool\";\n if (!seen) return base;\n const count = (seen.get(base) ?? 0) + 1;\n seen.set(base, count);\n return count === 1 ? base : `${base}_${count}`;\n}\n","import { stableToolId } from \"./revision\";\n\nexport interface McpToolManifestEntry {\n readonly toolId: string;\n readonly toolName: string;\n readonly description: string | null;\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n readonly annotations?: Readonly<Record<string, unknown>>;\n}\n\nexport interface McpToolManifest {\n readonly server: {\n readonly name: string | null;\n readonly version: string | null;\n readonly instructions: string | null;\n } | null;\n readonly tools: readonly McpToolManifestEntry[];\n}\n\nexport function extractMcpToolManifest(\n listToolsResult: unknown,\n metadata: {\n readonly serverInfo?: unknown;\n readonly instructions?: string;\n } = {},\n): McpToolManifest {\n const listed =\n listToolsResult &&\n typeof listToolsResult === \"object\" &&\n Array.isArray((listToolsResult as { tools?: unknown }).tools)\n ? (listToolsResult as { tools: unknown[] }).tools\n : [];\n const seen = new Map<string, number>();\n const tools = listed.flatMap((value): McpToolManifestEntry[] => {\n if (!value || typeof value !== \"object\") return [];\n const tool = value as Record<string, unknown>;\n if (typeof tool.name !== \"string\" || !tool.name.trim()) return [];\n const toolName = tool.name.trim();\n return [\n {\n toolId: stableToolId(toolName, seen),\n toolName,\n description: typeof tool.description === \"string\" ? tool.description : null,\n ...(tool.inputSchema !== undefined\n ? { inputSchema: tool.inputSchema }\n : tool.parameters !== undefined\n ? { inputSchema: tool.parameters }\n : {}),\n ...(tool.outputSchema !== undefined ? { outputSchema: tool.outputSchema } : {}),\n ...(tool.annotations && typeof tool.annotations === \"object\"\n ? { annotations: tool.annotations as Readonly<Record<string, unknown>> }\n : {}),\n },\n ];\n });\n const info =\n metadata.serverInfo && typeof metadata.serverInfo === \"object\"\n ? (metadata.serverInfo as Record<string, unknown>)\n : null;\n return {\n server: info\n ? {\n name: typeof info.name === \"string\" ? info.name : null,\n version: typeof info.version === \"string\" ? info.version : null,\n instructions: metadata.instructions ?? null,\n }\n : null,\n tools,\n };\n}\n\nexport function deriveMcpNamespace(input: {\n readonly name?: string | null;\n readonly endpoint?: string | null;\n readonly command?: string | null;\n}): string {\n const candidate =\n input.name?.trim() || hostname(input.endpoint) || basename(input.command) || \"mcp\";\n return stableToolId(candidate);\n}\n\nfunction hostname(value: string | null | undefined): string {\n if (!value || !URL.canParse(value)) return \"\";\n return new URL(value).hostname;\n}\n\nfunction basename(value: string | null | undefined): string {\n return value?.trim().split(/[\\\\/]/).pop() ?? \"\";\n}\n","import type { MCPServer } from \"@openai/agents\";\n\nexport const LOCAL_MCP_BRIDGE_CONTRACT_VERSION = 1 as const;\n\nexport type LocalMcpBridgeAuthority = \"connection\" | \"host\" | \"none\";\nexport type LocalMcpBridgeToolSurface = \"static_reviewed\";\n\nexport type LocalMcpBridgeDestination = Readonly<{\n origin: string;\n pathPrefix: string;\n}>;\n\n/**\n * Secret-free description of an in-process provider-to-MCP adapter.\n *\n * This is observability and registration metadata, not authorization. The\n * adapter must still revalidate its named authority before each physical\n * provider request and keep credentials outside tool results and schemas.\n */\nexport type LocalMcpBridgeDescriptor = Readonly<{\n contractVersion: typeof LOCAL_MCP_BRIDGE_CONTRACT_VERSION;\n adapterId: string;\n providerId: string;\n catalogIdentity: string;\n transport: \"in_process\";\n authority: LocalMcpBridgeAuthority;\n toolSurface: LocalMcpBridgeToolSurface;\n mutationReplay: \"safe_reads_only\";\n destinations: readonly LocalMcpBridgeDestination[];\n}>;\n\nexport interface LocalMcpBridgeServer extends MCPServer {\n readonly bridge: LocalMcpBridgeDescriptor;\n}\n\nexport interface LocalMcpBridgeAdapter<TConfig, TContext> {\n readonly adapterId: string;\n matches(config: TConfig): boolean;\n create(config: TConfig, context: TContext): LocalMcpBridgeServer;\n}\n\nexport function defineLocalMcpBridgeDescriptor(\n input: Omit<LocalMcpBridgeDescriptor, \"contractVersion\" | \"transport\">,\n): LocalMcpBridgeDescriptor {\n const adapterId = boundedIdentity(input.adapterId, \"adapterId\");\n const providerId = boundedIdentity(input.providerId, \"providerId\");\n const catalogIdentity = boundedIdentity(input.catalogIdentity, \"catalogIdentity\", 512);\n if (input.destinations.length === 0 || input.destinations.length > 32) {\n throw new Error(\"Local MCP bridge must declare 1-32 provider destinations\");\n }\n const destinations = input.destinations.map((destination) => {\n const url = new URL(destination.origin);\n if (url.protocol !== \"https:\" || url.origin !== destination.origin) {\n throw new Error(\"Local MCP bridge destinations must be exact HTTPS origins\");\n }\n if (\n !destination.pathPrefix.startsWith(\"/\") ||\n destination.pathPrefix.includes(\"\\\\\") ||\n destination.pathPrefix.includes(\"?\") ||\n destination.pathPrefix.includes(\"#\") ||\n new URL(destination.pathPrefix, url.origin).pathname !== destination.pathPrefix\n ) {\n throw new Error(\"Local MCP bridge destination pathPrefix must be an absolute URL path\");\n }\n return Object.freeze({ origin: url.origin, pathPrefix: destination.pathPrefix });\n });\n return Object.freeze({\n contractVersion: LOCAL_MCP_BRIDGE_CONTRACT_VERSION,\n adapterId,\n providerId,\n catalogIdentity,\n transport: \"in_process\",\n authority: input.authority,\n toolSurface: input.toolSurface,\n mutationReplay: input.mutationReplay,\n destinations: Object.freeze(destinations),\n });\n}\n\nexport function isLocalMcpBridgeServer(server: MCPServer): server is LocalMcpBridgeServer {\n const bridge = (server as Partial<LocalMcpBridgeServer>).bridge;\n return (\n bridge?.contractVersion === LOCAL_MCP_BRIDGE_CONTRACT_VERSION &&\n bridge.transport === \"in_process\"\n );\n}\n\n/**\n * Select exactly one adapter for a runtime catalog row. Ambiguous matches fail\n * closed so adding a bridge cannot silently replace another provider route.\n */\nexport function createLocalMcpBridgeFromAdapters<TConfig, TContext>(\n adapters: readonly LocalMcpBridgeAdapter<TConfig, TContext>[],\n config: TConfig,\n context: TContext,\n): LocalMcpBridgeServer | null {\n const matches = adapters.filter((adapter) => adapter.matches(config));\n if (matches.length === 0) return null;\n if (matches.length > 1) {\n throw new Error(\n `Multiple local MCP bridge adapters matched: ${matches.map((entry) => entry.adapterId).join(\", \")}`,\n );\n }\n const adapter = matches[0]!;\n const server = adapter.create(config, context);\n if (server.bridge.adapterId !== adapter.adapterId) {\n throw new Error(`Local MCP bridge adapter ${adapter.adapterId} returned mismatched metadata`);\n }\n return server;\n}\n\nfunction boundedIdentity(value: string, name: string, max = 128): string {\n if (value.length === 0 || value.length > max || /[\\u0000-\\u001f\\u007f]/u.test(value)) {\n throw new Error(`Local MCP bridge ${name} is invalid`);\n }\n return value;\n}\n","import type { CallToolResultContent, MCPCallToolOptions, MCPServer } from \"@openai/agents\";\nimport { load as parseYaml } from \"js-yaml\";\n\nimport { applyCredentialPlacements } from \"./auth\";\nimport {\n DEFAULT_INTEGRATION_RESPONSE_BYTES,\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n MAX_INTEGRATION_SPEC_BYTES,\n MAX_INTEGRATION_TOOLS,\n fetchWithDeadline,\n readIntegrationResponse,\n} from \"./http\";\nimport { canonicalJson, immutableRevisionId, sha256Hex, stableToolId } from \"./revision\";\nimport type {\n IntegrationCredentialResolver,\n IntegrationInvocationAuthority,\n IntegrationRevision,\n IntegrationToolDefinition,\n IntegrationTransport,\n JsonSchema,\n} from \"./types\";\nimport { IntegrationInvocationError, IntegrationProtocolError } from \"./types\";\n\nexport type OpenApiHttpMethod =\n | \"get\"\n | \"put\"\n | \"post\"\n | \"delete\"\n | \"patch\"\n | \"head\"\n | \"options\"\n | \"trace\";\n\nexport interface OpenApiParameterBinding {\n readonly name: string;\n readonly location: \"path\" | \"query\" | \"header\" | \"cookie\";\n readonly required: boolean;\n readonly schema: JsonSchema;\n readonly description?: string;\n}\n\nexport interface OpenApiOperationBinding {\n readonly method: OpenApiHttpMethod;\n readonly pathTemplate: string;\n readonly serverUrl: string;\n readonly parameters: readonly OpenApiParameterBinding[];\n readonly requestBody?: {\n readonly required: boolean;\n readonly contentTypes: readonly string[];\n readonly schemas: Readonly<Record<string, JsonSchema>>;\n };\n readonly requiredScopeAlternatives?: readonly (readonly string[])[];\n}\n\nexport type OpenApiRevision = IntegrationRevision<OpenApiOperationBinding, \"openapi\">;\n\nexport interface CompileOpenApiOptions {\n readonly definitionId: string;\n readonly sourceUrl?: string;\n readonly baseUrl?: string;\n readonly provider?: string;\n}\n\nexport interface OpenApiServerOptions {\n readonly revision: OpenApiRevision;\n readonly transport: IntegrationTransport;\n readonly credentialResolver?: IntegrationCredentialResolver;\n readonly authority: IntegrationInvocationAuthority;\n readonly timeoutMs?: number;\n readonly maxResponseBytes?: number;\n}\n\nexport type OpenApiAuthDiscovery =\n | { kind: \"none\" }\n | {\n kind: \"oauth2\";\n scopes: string[];\n }\n | {\n kind: \"api_key\";\n carrier: \"header\" | \"query\" | \"cookie\";\n name: string;\n }\n | { kind: \"http\"; scheme: string };\n\ntype LocalMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\nconst methods = new Set<OpenApiHttpMethod>([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nconst forbiddenParameterHeaders = new Set([\n \"host\",\n \"content-length\",\n \"connection\",\n \"transfer-encoding\",\n]);\n\nexport function parseOpenApiDocument(source: string | Uint8Array): Record<string, unknown> {\n const bytes = typeof source === \"string\" ? Buffer.byteLength(source) : source.byteLength;\n if (bytes === 0 || bytes > MAX_INTEGRATION_SPEC_BYTES) {\n throw new IntegrationProtocolError(\n \"openapi_spec_size\",\n `OpenAPI document must be between 1 and ${MAX_INTEGRATION_SPEC_BYTES} bytes`,\n );\n }\n const text =\n typeof source === \"string\" ? source : new TextDecoder(\"utf-8\", { fatal: true }).decode(source);\n let parsed: unknown;\n try {\n parsed = parseYaml(text, { json: true });\n } catch {\n throw new IntegrationProtocolError(\n \"openapi_parse\",\n \"OpenAPI document is not valid JSON or YAML\",\n );\n }\n if (\n !isRecord(parsed) ||\n typeof parsed.openapi !== \"string\" ||\n !/^3\\.(?:0|1)(?:\\.|$)/.test(parsed.openapi)\n ) {\n throw new IntegrationProtocolError(\n \"openapi_version\",\n \"Only OpenAPI 3.0 and 3.1 documents are supported\",\n );\n }\n if (!isRecord(parsed.paths)) {\n throw new IntegrationProtocolError(\"openapi_paths\", \"OpenAPI document has no paths object\");\n }\n return parsed;\n}\n\nexport function compileOpenApiRevision(\n source: string | Uint8Array | Record<string, unknown>,\n options: CompileOpenApiOptions,\n): OpenApiRevision {\n const document = isRecord(source) ? source : parseOpenApiDocument(source);\n const contentSha256 = sha256Hex(canonicalJson(document));\n const revisionId = immutableRevisionId(\"openapi\", contentSha256);\n const info = isRecord(document.info) ? document.info : {};\n const documentServers = readServers(document.servers, options.baseUrl, options.sourceUrl);\n const documentSecurity = readSecurity(document.security);\n const tools: IntegrationToolDefinition[] = [];\n const bindings: Record<string, OpenApiOperationBinding> = {};\n const seen = new Map<string, number>();\n\n for (const [pathTemplate, rawPathItem] of Object.entries(\n document.paths as Record<string, unknown>,\n )) {\n const pathItem = resolveObject(document, rawPathItem, \"path item\");\n const sharedParameters = readParameters(document, pathItem.parameters);\n const pathServers = readServers(pathItem.servers, undefined, undefined);\n for (const [rawMethod, rawOperation] of Object.entries(pathItem)) {\n const method = rawMethod.toLowerCase() as OpenApiHttpMethod;\n if (!methods.has(method) || !isRecord(rawOperation)) continue;\n const operation = resolveObject(document, rawOperation, \"operation\");\n const operationKey = operationIdentity(method, pathTemplate, operation.operationId);\n const id = stableToolId(operationKey, seen);\n const parameters = mergeParameters(\n sharedParameters,\n readParameters(document, operation.parameters),\n );\n const requestBody = readRequestBody(document, operation.requestBody);\n const serverUrl = firstServerUrl(\n readServers(operation.servers, undefined, undefined),\n pathServers,\n documentServers,\n );\n const requiredScopeAlternatives =\n operation.security === undefined ? documentSecurity : readSecurity(operation.security);\n const safety = classifyHttpSafety(method, operation);\n const inputSchema = operationInputSchema(parameters, requestBody);\n const outputSchema = operationOutputSchema(document, operation.responses);\n const summary = stringValue(operation.summary) ?? stringValue(operation.description);\n tools.push({\n id,\n operationKey,\n name: summary ?? `${method.toUpperCase()} ${pathTemplate}`,\n description: toolDescription(method, pathTemplate, operation, safety),\n inputSchema,\n ...(outputSchema ? { outputSchema } : {}),\n safety,\n approvalMode: safety === \"read\" ? \"never\" : \"ask\",\n deprecated: operation.deprecated === true,\n });\n bindings[id] = {\n method,\n pathTemplate,\n serverUrl,\n parameters,\n ...(requestBody ? { requestBody } : {}),\n ...(requiredScopeAlternatives.length > 0 ? { requiredScopeAlternatives } : {}),\n };\n if (tools.length > MAX_INTEGRATION_TOOLS) {\n throw new IntegrationProtocolError(\n \"openapi_tool_limit\",\n `OpenAPI document exceeds the ${MAX_INTEGRATION_TOOLS}-tool limit`,\n );\n }\n }\n }\n if (tools.length === 0) {\n throw new IntegrationProtocolError(\"openapi_empty\", \"OpenAPI document exposes no operations\");\n }\n return {\n id: revisionId,\n protocol: \"openapi\",\n definitionId: options.definitionId,\n contentSha256,\n source: {\n ...(options.sourceUrl ? { url: options.sourceUrl } : {}),\n ...(options.provider ? { provider: options.provider } : {}),\n },\n title: stringValue(info.title) ?? options.definitionId,\n ...(stringValue(info.description) ? { description: stringValue(info.description)! } : {}),\n ...(stringValue(info.version) ? { version: stringValue(info.version)! } : {}),\n tools,\n bindings,\n };\n}\n\nexport function discoverOpenApiAuth(document: Record<string, unknown>): OpenApiAuthDiscovery {\n const components = isRecord(document.components) ? document.components : {};\n const schemes = isRecord(components.securitySchemes) ? components.securitySchemes : {};\n for (const raw of Object.values(schemes)) {\n const scheme = resolveObject(document, raw, \"security scheme\");\n if (scheme.type === \"oauth2\") {\n const flows = isRecord(scheme.flows) ? scheme.flows : {};\n const scopes = new Set<string>();\n for (const flow of Object.values(flows)) {\n if (!isRecord(flow) || !isRecord(flow.scopes)) continue;\n for (const scope of Object.keys(flow.scopes)) scopes.add(scope);\n }\n return { kind: \"oauth2\", scopes: [...scopes].sort() };\n }\n if (\n scheme.type === \"apiKey\" &&\n (scheme.in === \"header\" || scheme.in === \"query\" || scheme.in === \"cookie\") &&\n typeof scheme.name === \"string\" &&\n scheme.name.length > 0\n ) {\n return { kind: \"api_key\", carrier: scheme.in, name: scheme.name };\n }\n if (scheme.type === \"http\" && typeof scheme.scheme === \"string\") {\n return { kind: \"http\", scheme: scheme.scheme.toLowerCase() };\n }\n }\n return { kind: \"none\" };\n}\n\nexport class OpenApiMcpServer implements MCPServer {\n readonly cacheToolsList = true;\n readonly useStructuredContent = true;\n readonly name: string;\n\n constructor(private readonly options: OpenApiServerOptions) {\n this.name = `openapi:${stableToolId(options.revision.definitionId)}`;\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n async invalidateToolsCache(): Promise<void> {}\n\n async listTools(): Promise<LocalMcpTool[]> {\n return this.options.revision.tools.map(\n (tool) =>\n ({\n name: tool.id,\n description: tool.description,\n inputSchema: normalizeMcpSchema(tool.inputSchema),\n annotations: {\n readOnlyHint: tool.safety === \"read\",\n destructiveHint: tool.safety === \"destructive\",\n idempotentHint: isIdempotentMethod(this.options.revision.bindings[tool.id]?.method),\n openWorldHint: true,\n },\n _meta: {\n \"opengeni/approvalMode\": tool.approvalMode,\n \"opengeni/operationKey\": tool.operationKey,\n \"opengeni/revisionId\": this.options.revision.id,\n },\n }) as LocalMcpTool,\n );\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n _meta?: Record<string, unknown> | null,\n callOptions?: MCPCallToolOptions,\n ): Promise<CallToolResultContent> {\n const result = await invokeOpenApiOperation(\n this.options,\n toolName,\n args ?? {},\n callOptions?.signal,\n );\n const content = [\n {\n type: \"text\" as const,\n text: JSON.stringify(result),\n },\n ] as CallToolResultContent;\n content.structuredContent = result as Record<string, unknown>;\n content.isError = result.ok === false;\n return content;\n }\n}\n\nexport function createOpenApiMcpServer(options: OpenApiServerOptions): MCPServer {\n return new OpenApiMcpServer(options);\n}\n\nexport async function invokeOpenApiOperation(\n options: OpenApiServerOptions,\n toolId: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const binding = options.revision.bindings[toolId];\n if (!binding) {\n throw new IntegrationInvocationError(\n \"operation_not_found\",\n \"Integration operation is not present in the frozen revision\",\n \"not_started\",\n false,\n );\n }\n const firstCredential = await resolveOpenApiCredential(options, binding, toolId, args, false);\n let response = await sendOpenApiRequest(options, binding, args, firstCredential, signal);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveOpenApiCredential(options, binding, toolId, args, true);\n if (isReplaySafeMethod(binding.method) && refreshed) {\n await response.body?.cancel().catch(() => undefined);\n response = await sendOpenApiRequest(options, binding, args, refreshed, signal);\n } else {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n isReplaySafeMethod(binding.method) ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"Integration attempted to redirect a credential-bearing request\",\n binding.method === \"get\" || binding.method === \"head\" ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n const payload = await readIntegrationResponse(\n response,\n options.maxResponseBytes ?? DEFAULT_INTEGRATION_RESPONSE_BYTES,\n );\n const result = {\n ok: response.ok,\n status: response.status,\n contentType: payload.contentType,\n data: payload.data,\n };\n if (!response.ok && (response.status === 401 || response.status === 403)) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n binding.method === \"get\" || binding.method === \"head\" ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n return result;\n}\n\nasync function resolveOpenApiCredential(\n options: OpenApiServerOptions,\n binding: OpenApiOperationBinding,\n toolId: string,\n args: Record<string, unknown>,\n forceRefresh: boolean,\n): Promise<Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>> {\n if (!options.credentialResolver || !options.authority.connectionRef) return null;\n const destinationUrl = buildOperationUrl(binding, args).toString();\n const credential = await options.credentialResolver.resolve({\n ...options.authority,\n protocol: \"openapi\",\n definitionId: options.revision.definitionId,\n revisionId: options.revision.id,\n operationKey: toolId,\n destinationUrl,\n ...(binding.requiredScopeAlternatives\n ? { requiredScopeAlternatives: binding.requiredScopeAlternatives }\n : {}),\n ...(forceRefresh ? { forceRefresh: true } : {}),\n });\n if (!credential && !forceRefresh) {\n throw new IntegrationInvocationError(\n \"connection_required\",\n \"This integration needs a connected account\",\n \"not_started\",\n false,\n );\n }\n return credential;\n}\n\nasync function sendOpenApiRequest(\n options: OpenApiServerOptions,\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n credential: Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>,\n signal?: AbortSignal,\n): Promise<Response> {\n const url = buildOperationUrl(binding, args);\n const headers = buildOperationHeaders(binding, args);\n const body = buildOperationBody(binding, args, headers);\n if (credential) applyCredentialPlacements(url, headers, credential);\n if (credential?.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await credential.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n \"not_started\",\n false,\n );\n }\n }\n return await fetchWithDeadline(\n options.transport,\n url,\n {\n method: binding.method.toUpperCase(),\n headers,\n ...(body !== undefined ? { body } : {}),\n ...(signal ? { signal } : {}),\n },\n options.timeoutMs ?? DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n}\n\nfunction readServers(\n value: unknown,\n explicitBaseUrl: string | undefined,\n sourceUrl: string | undefined,\n): string[] {\n if (explicitBaseUrl) return [normalizeServerUrl(explicitBaseUrl)];\n const servers = Array.isArray(value)\n ? value.flatMap((entry): string[] =>\n isRecord(entry) && typeof entry.url === \"string\"\n ? [resolveServerUrl(entry.url, sourceUrl)]\n : [],\n )\n : [];\n if (servers.length > 0) return servers;\n if (sourceUrl && URL.canParse(sourceUrl)) {\n const source = new URL(sourceUrl);\n return [`${source.origin}/`];\n }\n return [];\n}\n\nfunction firstServerUrl(...groups: readonly string[][]): string {\n const server = groups.flat().find(Boolean);\n if (!server) {\n throw new IntegrationProtocolError(\n \"openapi_server_missing\",\n \"OpenAPI operation has no resolvable server URL\",\n );\n }\n return server;\n}\n\nfunction resolveServerUrl(value: string, sourceUrl?: string): string {\n if (/[{}]/.test(value)) {\n throw new IntegrationProtocolError(\n \"openapi_server_variable\",\n \"OpenAPI server variables require an explicit resolved base URL\",\n );\n }\n try {\n return normalizeServerUrl(sourceUrl ? new URL(value, sourceUrl).toString() : value);\n } catch {\n throw new IntegrationProtocolError(\"openapi_server_invalid\", \"OpenAPI server URL is invalid\");\n }\n}\n\nfunction normalizeServerUrl(value: string): string {\n const url = new URL(value);\n if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.hash) {\n throw new IntegrationProtocolError(\"openapi_server_invalid\", \"OpenAPI server URL is invalid\");\n }\n return url.toString();\n}\n\nfunction readParameters(\n document: Record<string, unknown>,\n value: unknown,\n): OpenApiParameterBinding[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((raw): OpenApiParameterBinding[] => {\n const parameter = resolveObject(document, raw, \"parameter\");\n const location = parameter.in;\n if (\n typeof parameter.name !== \"string\" ||\n (location !== \"path\" &&\n location !== \"query\" &&\n location !== \"header\" &&\n location !== \"cookie\")\n ) {\n return [];\n }\n if (location === \"header\" && forbiddenParameterHeaders.has(parameter.name.toLowerCase()))\n return [];\n return [\n {\n name: parameter.name,\n location,\n required: location === \"path\" || parameter.required === true,\n schema: dereferenceSchema(document, parameter.schema),\n ...(stringValue(parameter.description)\n ? { description: stringValue(parameter.description)! }\n : {}),\n },\n ];\n });\n}\n\nfunction mergeParameters(\n base: readonly OpenApiParameterBinding[],\n override: readonly OpenApiParameterBinding[],\n): OpenApiParameterBinding[] {\n const merged = new Map(base.map((entry) => [`${entry.location}:${entry.name}`, entry]));\n for (const entry of override) merged.set(`${entry.location}:${entry.name}`, entry);\n return [...merged.values()];\n}\n\nfunction readRequestBody(\n document: Record<string, unknown>,\n value: unknown,\n): OpenApiOperationBinding[\"requestBody\"] | undefined {\n if (value === undefined) return undefined;\n const body = resolveObject(document, value, \"request body\");\n if (!isRecord(body.content)) return undefined;\n const schemas: Record<string, JsonSchema> = {};\n for (const [contentType, rawMedia] of Object.entries(body.content)) {\n if (!isRecord(rawMedia)) continue;\n schemas[contentType.toLowerCase()] = dereferenceSchema(document, rawMedia.schema);\n }\n const contentTypes = Object.keys(schemas);\n return contentTypes.length === 0\n ? undefined\n : { required: body.required === true, contentTypes, schemas };\n}\n\nfunction operationInputSchema(\n parameters: readonly OpenApiParameterBinding[],\n body: OpenApiOperationBinding[\"requestBody\"],\n): JsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const location of [\"path\", \"query\", \"header\", \"cookie\"] as const) {\n const group = parameters.filter((entry) => entry.location === location);\n if (group.length === 0) continue;\n properties[location] = {\n type: \"object\",\n properties: Object.fromEntries(\n group.map((entry) => [\n entry.name,\n { ...entry.schema, ...(entry.description ? { description: entry.description } : {}) },\n ]),\n ),\n required: group.filter((entry) => entry.required).map((entry) => entry.name),\n additionalProperties: false,\n };\n if (group.some((entry) => entry.required)) required.push(location);\n }\n if (body) {\n properties.body = body.schemas[body.contentTypes[0]!] ?? {};\n if (body.contentTypes.length > 1) {\n properties.contentType = { type: \"string\", enum: body.contentTypes };\n }\n if (body.required) required.push(\"body\");\n }\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\nfunction operationOutputSchema(\n document: Record<string, unknown>,\n value: unknown,\n): JsonSchema | undefined {\n if (!isRecord(value)) return undefined;\n for (const status of [\"200\", \"201\", \"202\", \"203\", \"204\", \"default\"]) {\n if (!(status in value)) continue;\n const response = resolveObject(document, value[status], \"response\");\n if (!isRecord(response.content)) return undefined;\n for (const media of Object.values(response.content)) {\n if (isRecord(media) && media.schema !== undefined) {\n return dereferenceSchema(document, media.schema);\n }\n }\n }\n return undefined;\n}\n\nfunction readSecurity(value: unknown): readonly (readonly string[])[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry): string[][] => {\n if (!isRecord(entry)) return [];\n const scopes = Object.values(entry).flatMap((raw) =>\n Array.isArray(raw) ? raw.filter((scope): scope is string => typeof scope === \"string\") : [],\n );\n return scopes.length > 0 ? [[...new Set(scopes)].sort()] : [];\n });\n}\n\nfunction classifyHttpSafety(\n method: OpenApiHttpMethod,\n operation: Record<string, unknown>,\n): IntegrationToolDefinition[\"safety\"] {\n if (method === \"get\" || method === \"head\" || method === \"options\") return \"read\";\n const text =\n `${stringValue(operation.operationId) ?? \"\"} ${stringValue(operation.summary) ?? \"\"}`.toLowerCase();\n return method === \"delete\" || /\\b(delete|destroy|remove|revoke|cancel|purge)\\b/.test(text)\n ? \"destructive\"\n : \"write\";\n}\n\nfunction operationIdentity(method: OpenApiHttpMethod, path: string, operationId: unknown): string {\n return typeof operationId === \"string\" && operationId.trim()\n ? operationId.trim()\n : `${method}_${path}`;\n}\n\nfunction toolDescription(\n method: OpenApiHttpMethod,\n path: string,\n operation: Record<string, unknown>,\n safety: IntegrationToolDefinition[\"safety\"],\n): string {\n const description = stringValue(operation.description) ?? stringValue(operation.summary);\n const approval =\n safety === \"read\" ? \"Read-only.\" : \"Changes external state and requires approval.\";\n return `${description ? `${description.trim()} ` : \"\"}${method.toUpperCase()} ${path}. ${approval}`.trim();\n}\n\nfunction isIdempotentMethod(method: OpenApiHttpMethod | undefined): boolean {\n return (\n method === \"get\" ||\n method === \"head\" ||\n method === \"options\" ||\n method === \"put\" ||\n method === \"delete\"\n );\n}\n\nfunction isReplaySafeMethod(method: OpenApiHttpMethod): boolean {\n return method === \"get\" || method === \"head\" || method === \"options\";\n}\n\nfunction buildOperationUrl(binding: OpenApiOperationBinding, args: Record<string, unknown>): URL {\n const pathArgs = objectValue(args.path);\n const path = binding.pathTemplate.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n const value = pathArgs[name];\n if (value === undefined || value === null) {\n throw new IntegrationInvocationError(\n \"path_parameter_missing\",\n \"A required integration path parameter is missing\",\n \"not_started\",\n false,\n );\n }\n return encodeURIComponent(scalarString(value));\n });\n const base = new URL(binding.serverUrl);\n const url = new URL(\n path.replace(/^\\//, \"\"),\n base.toString().endsWith(\"/\") ? base : new URL(`${base}/`),\n );\n const query = objectValue(args.query);\n for (const [name, value] of Object.entries(query)) appendQueryValue(url, name, value);\n return url;\n}\n\nfunction buildOperationHeaders(\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n): Headers {\n const headers = new Headers({ accept: \"application/json, text/plain;q=0.9, */*;q=0.5\" });\n for (const [name, value] of Object.entries(objectValue(args.header))) {\n if (forbiddenParameterHeaders.has(name.toLowerCase())) continue;\n headers.set(name, scalarString(value));\n }\n const cookies = Object.entries(objectValue(args.cookie)).map(\n ([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(scalarString(value))}`,\n );\n if (cookies.length > 0) headers.set(\"cookie\", cookies.join(\"; \"));\n if (binding.requestBody && args.body !== undefined) {\n const requested =\n typeof args.contentType === \"string\" ? args.contentType.toLowerCase() : undefined;\n const contentType =\n requested && binding.requestBody.contentTypes.includes(requested)\n ? requested\n : binding.requestBody.contentTypes[0]!;\n headers.set(\"content-type\", contentType);\n }\n return headers;\n}\n\nfunction buildOperationBody(\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n headers: Headers,\n): BodyInit | undefined {\n if (!binding.requestBody || args.body === undefined) return undefined;\n const contentType = headers.get(\"content-type\") ?? \"application/json\";\n if (contentType === \"application/x-www-form-urlencoded\") {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(objectValue(args.body)))\n appendSearchParam(params, key, value);\n return params;\n }\n if (contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n return JSON.stringify(args.body);\n }\n if (typeof args.body === \"string\") return args.body;\n throw new IntegrationInvocationError(\n \"request_body_unsupported\",\n \"This operation requires a text body for the selected content type\",\n \"not_started\",\n false,\n );\n}\n\nfunction appendQueryValue(url: URL, name: string, value: unknown): void {\n if (Array.isArray(value)) {\n for (const entry of value) url.searchParams.append(name, scalarString(entry));\n } else if (value !== undefined && value !== null) {\n url.searchParams.append(name, scalarString(value));\n }\n}\n\nfunction appendSearchParam(params: URLSearchParams, name: string, value: unknown): void {\n if (Array.isArray(value)) {\n for (const entry of value) params.append(name, scalarString(entry));\n } else if (value !== undefined && value !== null) {\n params.append(name, scalarString(value));\n }\n}\n\nfunction scalarString(value: unknown): string {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n throw new IntegrationInvocationError(\n \"parameter_invalid\",\n \"Integration parameters must be strings, numbers, booleans, or arrays of them\",\n \"not_started\",\n false,\n );\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction resolveObject(\n document: Record<string, unknown>,\n value: unknown,\n label: string,\n): Record<string, unknown> {\n const resolved = resolveLocalRef(document, value);\n if (!isRecord(resolved)) {\n throw new IntegrationProtocolError(\"openapi_shape\", `OpenAPI ${label} is invalid`);\n }\n return resolved;\n}\n\nfunction resolveLocalRef(document: Record<string, unknown>, value: unknown): unknown {\n if (!isRecord(value) || typeof value.$ref !== \"string\") return value;\n if (!value.$ref.startsWith(\"#/\")) {\n throw new IntegrationProtocolError(\n \"openapi_external_ref\",\n \"External OpenAPI references are not supported; bundle the document first\",\n );\n }\n return value.$ref\n .slice(2)\n .split(\"/\")\n .map((part) => part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .reduce<unknown>((current, part) => (isRecord(current) ? current[part] : undefined), document);\n}\n\nfunction dereferenceSchema(\n document: Record<string, unknown>,\n value: unknown,\n seen = new Set<string>(),\n depth = 0,\n): JsonSchema {\n if (depth > 20) return {};\n if (isRecord(value) && typeof value.$ref === \"string\") {\n if (seen.has(value.$ref)) return {};\n const nextSeen = new Set(seen).add(value.$ref);\n return dereferenceSchema(document, resolveLocalRef(document, value), nextSeen, depth + 1);\n }\n if (!isRecord(value)) return {};\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"properties\" && isRecord(entry)) {\n result.properties = Object.fromEntries(\n Object.entries(entry).map(([name, schema]) => [\n name,\n dereferenceSchema(document, schema, seen, depth + 1),\n ]),\n );\n } else if (key === \"items\") {\n result.items = dereferenceSchema(document, entry, seen, depth + 1);\n } else if (key === \"allOf\" || key === \"anyOf\" || key === \"oneOf\") {\n result[key] = Array.isArray(entry)\n ? entry.map((schema) => dereferenceSchema(document, schema, seen, depth + 1))\n : [];\n } else if (key !== \"$ref\") {\n result[key] = entry;\n }\n }\n return result;\n}\n\nfunction normalizeMcpSchema(schema: JsonSchema): LocalMcpTool[\"inputSchema\"] {\n return {\n type: \"object\",\n properties: isRecord(schema.properties) ? schema.properties : {},\n required: Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [],\n additionalProperties: schema.additionalProperties === true,\n };\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { IntegrationProtocolError } from \"./types\";\n\nexport interface IntegrationDefinitionOAuth2Authentication {\n readonly kind: \"oauth2\";\n readonly provider: \"google\" | \"microsoft\";\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly scopes: readonly string[];\n readonly tokenPlacement: {\n readonly carrier: \"header\";\n readonly name: \"Authorization\";\n readonly prefix: \"Bearer \";\n };\n}\n\nexport type IntegrationDefinitionSource =\n | Readonly<{\n kind: \"google_discovery\";\n url: string;\n }>\n | Readonly<{\n kind: \"openapi\";\n url: string;\n operationPathPrefixes?: readonly string[];\n }>;\n\nexport interface IntegrationDefinition {\n readonly id: string;\n readonly name: string;\n readonly summary: string;\n readonly protocol: \"openapi\";\n readonly provider: Readonly<{\n id: \"google\" | \"microsoft\";\n domain: string;\n }>;\n readonly source: IntegrationDefinitionSource;\n readonly baseUrl: string;\n readonly authentication: IntegrationDefinitionOAuth2Authentication;\n readonly healthCheck?: Readonly<{\n operationKey: string;\n arguments: Readonly<Record<string, unknown>>;\n }>;\n readonly facets: readonly IntegrationFacetDefinition[];\n}\n\nexport interface IntegrationFacetDefinition {\n readonly facetKey: string;\n readonly kind: \"knowledge_source\" | \"inbound_trigger\" | \"delivery_destination\" | \"identity_link\";\n readonly configSchema: Readonly<Record<string, unknown>>;\n readonly capabilities: Readonly<Record<string, unknown>>;\n}\n\nconst accountIdentityFacet = (provider: \"google\" | \"microsoft\"): IntegrationFacetDefinition => ({\n facetKey: \"account-identity\",\n kind: \"identity_link\",\n configSchema: { type: \"object\", properties: {}, additionalProperties: false },\n capabilities: {\n provider,\n connectionRequired: true,\n identity: \"connected_account\",\n },\n});\n\nconst driveKnowledgeFacet = (\n provider: \"google-drive\" | \"microsoft-onedrive\",\n): IntegrationFacetDefinition => ({\n facetKey: \"drive-content\",\n kind: \"knowledge_source\",\n configSchema: {\n type: \"object\",\n required: [\"sources\", \"destination\", \"syncCadence\", \"readPolicy\"],\n properties: {\n sources: {\n type: \"array\",\n minItems: 1,\n maxItems: 100,\n items: {\n type: \"object\",\n required: [\"id\", \"name\", \"mimeType\", \"sourceKind\", \"includeDescendants\"],\n properties: {\n id: { type: \"string\", minLength: 1, maxLength: 512 },\n name: { type: \"string\", minLength: 1, maxLength: 1024 },\n mimeType: { type: \"string\", minLength: 1, maxLength: 256 },\n driveId: { type: \"string\", minLength: 1, maxLength: 512 },\n sourceKind: {\n type: \"string\",\n enum:\n provider === \"google-drive\"\n ? [\"my_drive\", \"shared_drive\", \"folder\"]\n : [\"my_drive\", \"shared_library\", \"folder\"],\n },\n includeDescendants: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n destination: {\n type: \"object\",\n required: [\"authorityKind\", \"authorityAccountId\"],\n properties: {\n authorityKind: {\n type: \"string\",\n enum: [\"organization\", \"workspace\", \"personal\"],\n },\n authorityAccountId: { type: \"string\", minLength: 1, maxLength: 128 },\n authorityWorkspaceId: { type: \"string\", minLength: 1, maxLength: 128 },\n authoritySubjectId: { type: \"string\", minLength: 1, maxLength: 512 },\n collectionId: { type: \"string\", minLength: 1, maxLength: 512 },\n },\n additionalProperties: false,\n },\n syncCadence: { type: \"string\", enum: [\"manual\", \"hourly\", \"daily\"] },\n readPolicy: { type: \"string\", enum: [\"allow\", \"ask\", \"block\"] },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n sync: \"incremental\",\n cursor: provider === \"google-drive\" ? \"page_token\" : \"delta_link\",\n },\n});\n\nconst mailboxFacets = (\n provider: \"microsoft-outlook-mail\",\n): readonly IntegrationFacetDefinition[] => [\n {\n facetKey: \"mail-inbox\",\n kind: \"inbound_trigger\",\n configSchema: {\n type: \"object\",\n properties: {\n folder: { type: \"string\", minLength: 1, maxLength: 256 },\n unreadOnly: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n delivery: \"poll\",\n cursor: \"delta_link\",\n },\n },\n {\n facetKey: \"mail-delivery\",\n kind: \"delivery_destination\",\n configSchema: {\n type: \"object\",\n properties: {\n fromAlias: { type: \"string\", minLength: 1, maxLength: 512 },\n saveToSent: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n delivery: \"email\",\n },\n },\n accountIdentityFacet(\"microsoft\"),\n];\n\nconst googleDiscoveryUrl = (service: string, version: string): string =>\n `https://www.googleapis.com/discovery/v1/apis/${service}/${version}/rest`;\n\nconst googleOAuth = (scopes: readonly string[]): IntegrationDefinitionOAuth2Authentication => ({\n kind: \"oauth2\",\n provider: \"google\",\n authorizationUrl: \"https://accounts.google.com/o/oauth2/v2/auth\",\n tokenUrl: \"https://oauth2.googleapis.com/token\",\n scopes: [\"openid\", \"email\", \"profile\", ...scopes],\n tokenPlacement: { carrier: \"header\", name: \"Authorization\", prefix: \"Bearer \" },\n});\n\nexport const GOOGLE_DRIVE_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"google-drive\",\n name: \"Google Drive\",\n summary: \"Files, folders, permissions, and shared drives.\",\n protocol: \"openapi\",\n provider: { id: \"google\", domain: \"www.googleapis.com\" },\n source: { kind: \"google_discovery\", url: googleDiscoveryUrl(\"drive\", \"v3\") },\n baseUrl: \"https://www.googleapis.com/drive/v3/\",\n authentication: googleOAuth([\"https://www.googleapis.com/auth/drive\"]),\n healthCheck: {\n operationKey: \"drive.about.get\",\n arguments: { query: { fields: \"user\" } },\n },\n facets: [driveKnowledgeFacet(\"google-drive\"), accountIdentityFacet(\"google\")],\n};\n\nexport const MICROSOFT_GRAPH_OPENAPI_URL =\n \"https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/openapi/v1.0/openapi.yaml\";\nexport const MICROSOFT_GRAPH_BASE_URL = \"https://graph.microsoft.com/v1.0\";\n\nconst microsoftOAuth = (scopes: readonly string[]): IntegrationDefinitionOAuth2Authentication => ({\n kind: \"oauth2\",\n provider: \"microsoft\",\n authorizationUrl: \"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\n tokenUrl: \"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\n scopes: [\"offline_access\", \"User.Read\", ...scopes],\n tokenPlacement: { carrier: \"header\", name: \"Authorization\", prefix: \"Bearer \" },\n});\n\nexport const MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-mail\",\n name: \"Outlook Mail\",\n summary: \"Messages, folders, attachments, settings, and sending mail.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n operationPathPrefixes: [\n \"/me/messages\",\n \"/me/mailFolders\",\n \"/me/sendMail\",\n \"/me/getMailTips\",\n \"/me/inferenceClassification\",\n \"/me/mailboxSettings\",\n \"/me/outlook\",\n ],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Mail.ReadWrite\", \"Mail.Send\", \"MailboxSettings.ReadWrite\"]),\n facets: mailboxFacets(\"microsoft-outlook-mail\"),\n};\n\nexport const MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-calendar\",\n name: \"Outlook Calendar\",\n summary: \"Calendars, events, availability, and scheduling.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n operationPathPrefixes: [\n \"/me/calendar\",\n \"/me/calendars\",\n \"/me/calendarGroups\",\n \"/me/calendarView\",\n \"/me/events\",\n \"/me/findMeetingTimes\",\n \"/me/reminderView\",\n ],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Calendars.ReadWrite\"]),\n facets: [\n {\n facetKey: \"calendar-events\",\n kind: \"inbound_trigger\",\n configSchema: {\n type: \"object\",\n properties: {\n calendarId: { type: \"string\", minLength: 1, maxLength: 512 },\n lookaheadDays: { type: \"integer\", minimum: 1, maximum: 365 },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider: \"microsoft-outlook-calendar\",\n connectionRequired: true,\n delivery: \"poll\",\n cursor: \"delta_link\",\n },\n },\n {\n facetKey: \"calendar-delivery\",\n kind: \"delivery_destination\",\n configSchema: {\n type: \"object\",\n properties: {\n calendarId: { type: \"string\", minLength: 1, maxLength: 512 },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider: \"microsoft-outlook-calendar\",\n connectionRequired: true,\n delivery: \"calendar_event\",\n },\n },\n accountIdentityFacet(\"microsoft\"),\n ],\n};\n\nexport const MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-contacts\",\n name: \"Outlook Contacts\",\n summary: \"Contacts, contact folders, and people suggestions.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n operationPathPrefixes: [\"/me/contacts\", \"/me/contactFolders\", \"/me/people\"],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Contacts.ReadWrite\", \"People.Read.All\"]),\n facets: [accountIdentityFacet(\"microsoft\")],\n};\n\nexport const MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-onedrive\",\n name: \"OneDrive\",\n summary: \"Drives, files, folders, sharing links, and permissions.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n operationPathPrefixes: [\"/me/drive\", \"/me/drives\", \"/me/followedSites\", \"/drives\", \"/shares\"],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Files.ReadWrite.All\", \"Sites.ReadWrite.All\"]),\n facets: [driveKnowledgeFacet(\"microsoft-onedrive\"), accountIdentityFacet(\"microsoft\")],\n};\n\nexport const CORE_INTEGRATION_DEFINITIONS: readonly IntegrationDefinition[] = [\n GOOGLE_DRIVE_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION,\n MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION,\n];\n\nexport function integrationDefinitionById(id: string): IntegrationDefinition | undefined {\n return CORE_INTEGRATION_DEFINITIONS.find((definition) => definition.id === id);\n}\n\nexport function integrationDefinitionProviderDomain(definition: IntegrationDefinition): string {\n return definition.provider.domain;\n}\n\nexport function integrationFacetDefinitions(\n definitionId: string | null | undefined,\n): readonly IntegrationFacetDefinition[] {\n return definitionId ? (integrationDefinitionById(definitionId)?.facets ?? []) : [];\n}\n\nexport function filterOpenApiDocumentForDefinition(\n document: Record<string, unknown>,\n definition: IntegrationDefinition,\n): Record<string, unknown> {\n if (definition.source.kind !== \"openapi\" || !definition.source.operationPathPrefixes?.length) {\n return document;\n }\n const operationPathPrefixes = definition.source.operationPathPrefixes;\n if (!isRecord(document.paths)) {\n throw new IntegrationProtocolError(\"openapi_paths\", \"OpenAPI document has no paths object\");\n }\n const paths = Object.fromEntries(\n Object.entries(document.paths).filter(([path]) =>\n operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)),\n ),\n );\n if (Object.keys(paths).length === 0) {\n throw new IntegrationProtocolError(\n \"integration_definition_empty\",\n `${definition.name} did not match any operations in the supplied OpenAPI document`,\n );\n }\n return {\n ...document,\n paths,\n servers: [{ url: definition.baseUrl }],\n };\n}\n\nexport function googleDiscoveryToOpenApi(discovery: unknown): Record<string, unknown> {\n if (!isRecord(discovery)) {\n throw new IntegrationProtocolError(\n \"google_discovery_shape\",\n \"Google Discovery document is invalid\",\n );\n }\n const rootUrl = stringValue(discovery.rootUrl) ?? stringValue(discovery.baseUrl);\n const servicePath = stringValue(discovery.servicePath) ?? \"\";\n if (!rootUrl || !URL.canParse(rootUrl)) {\n throw new IntegrationProtocolError(\n \"google_discovery_server\",\n \"Google Discovery document has no valid root URL\",\n );\n }\n const paths: Record<string, unknown> = {};\n collectGoogleMethods(discovery, discovery.methods, paths);\n collectGoogleResources(discovery, discovery.resources, paths);\n if (Object.keys(paths).length === 0) {\n throw new IntegrationProtocolError(\n \"google_discovery_empty\",\n \"Google Discovery document exposes no methods\",\n );\n }\n const scopes =\n isRecord(discovery.auth) && isRecord(discovery.auth.oauth2)\n ? discovery.auth.oauth2.scopes\n : undefined;\n const scopeMap = isRecord(scopes)\n ? Object.fromEntries(\n Object.entries(scopes).map(([scope, value]) => [\n scope,\n isRecord(value) && typeof value.description === \"string\" ? value.description : \"\",\n ]),\n )\n : {};\n return {\n openapi: \"3.1.0\",\n info: {\n title: stringValue(discovery.title) ?? stringValue(discovery.name) ?? \"Google API\",\n description: stringValue(discovery.description) ?? \"Google Discovery API\",\n version: stringValue(discovery.version) ?? \"v1\",\n },\n servers: [{ url: new URL(servicePath, rootUrl).toString() }],\n paths,\n components: {\n schemas: Object.fromEntries(\n Object.entries(isRecord(discovery.schemas) ? discovery.schemas : {}).map(\n ([name, schema]) => [name, convertGoogleSchema(schema)],\n ),\n ),\n securitySchemes: {\n googleOAuth2: {\n type: \"oauth2\",\n flows: {\n authorizationCode: {\n authorizationUrl: \"https://accounts.google.com/o/oauth2/v2/auth\",\n tokenUrl: \"https://oauth2.googleapis.com/token\",\n scopes: scopeMap,\n },\n },\n },\n },\n },\n security: Object.keys(scopeMap).length > 0 ? [{ googleOAuth2: [] }] : [],\n };\n}\n\nfunction collectGoogleResources(\n document: Record<string, unknown>,\n value: unknown,\n paths: Record<string, unknown>,\n): void {\n if (!isRecord(value)) return;\n for (const resource of Object.values(value)) {\n if (!isRecord(resource)) continue;\n collectGoogleMethods(document, resource.methods, paths);\n collectGoogleResources(document, resource.resources, paths);\n }\n}\n\nfunction collectGoogleMethods(\n document: Record<string, unknown>,\n value: unknown,\n paths: Record<string, unknown>,\n): void {\n if (!isRecord(value)) return;\n for (const [fallbackId, rawMethod] of Object.entries(value)) {\n if (!isRecord(rawMethod)) continue;\n const path = stringValue(rawMethod.path);\n const httpMethod = stringValue(rawMethod.httpMethod)?.toLowerCase();\n if (!path || !httpMethod) continue;\n const parameters = Object.entries(isRecord(rawMethod.parameters) ? rawMethod.parameters : {})\n .sort(([left], [right]) => left.localeCompare(right))\n .flatMap(([name, rawParameter]): Record<string, unknown>[] => {\n if (!isRecord(rawParameter)) return [];\n const location = rawParameter.location === \"path\" ? \"path\" : \"query\";\n return [\n {\n name,\n in: location,\n required: location === \"path\" || rawParameter.required === true,\n ...(stringValue(rawParameter.description)\n ? { description: stringValue(rawParameter.description) }\n : {}),\n schema: convertGoogleSchema(rawParameter),\n },\n ];\n });\n const requestRef = isRecord(rawMethod.request)\n ? stringValue(rawMethod.request.$ref)\n : undefined;\n const responseRef = isRecord(rawMethod.response)\n ? stringValue(rawMethod.response.$ref)\n : undefined;\n const operation: Record<string, unknown> = {\n operationId: stringValue(rawMethod.id) ?? fallbackId,\n // Discovery descriptions are often full documentation paragraphs. Keep\n // them as descriptions and use the stable method identity for the short\n // OpenGeni tool display name.\n summary: stringValue(rawMethod.id) ?? fallbackId,\n description: stringValue(rawMethod.description),\n parameters,\n responses: {\n \"200\": {\n description: \"Successful response\",\n ...(responseRef\n ? {\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${escapeJsonPointer(responseRef)}` },\n },\n },\n }\n : {}),\n },\n },\n ...(Array.isArray(rawMethod.scopes) && rawMethod.scopes.length > 0\n ? { security: [{ googleOAuth2: rawMethod.scopes }] }\n : {}),\n };\n if (requestRef) {\n operation.requestBody = {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${escapeJsonPointer(requestRef)}` },\n },\n },\n };\n }\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const existing = isRecord(paths[normalizedPath]) ? paths[normalizedPath] : {};\n paths[normalizedPath] = { ...existing, [httpMethod]: operation };\n }\n}\n\nfunction convertGoogleSchema(value: unknown, depth = 0): Record<string, unknown> {\n if (!isRecord(value) || depth > 20) return {};\n if (typeof value.$ref === \"string\") {\n return { $ref: `#/components/schemas/${escapeJsonPointer(value.$ref)}` };\n }\n const result: Record<string, unknown> = {};\n const type = stringValue(value.type);\n if (type) result.type = type === \"any\" ? undefined : type;\n for (const key of [\n \"description\",\n \"format\",\n \"pattern\",\n \"minimum\",\n \"maximum\",\n \"default\",\n ] as const) {\n if (value[key] !== undefined) result[key] = value[key];\n }\n if (Array.isArray(value.enum)) result.enum = value.enum;\n if (isRecord(value.properties)) {\n result.type = result.type ?? \"object\";\n result.properties = Object.fromEntries(\n Object.entries(value.properties).map(([name, schema]) => [\n name,\n convertGoogleSchema(schema, depth + 1),\n ]),\n );\n }\n if (value.items !== undefined) {\n result.type = result.type ?? \"array\";\n result.items = convertGoogleSchema(value.items, depth + 1);\n }\n if (value.additionalProperties !== undefined) {\n result.additionalProperties =\n value.additionalProperties === true\n ? true\n : convertGoogleSchema(value.additionalProperties, depth + 1);\n }\n if (Array.isArray(value.required)) result.required = value.required;\n return Object.fromEntries(Object.entries(result).filter(([, entry]) => entry !== undefined));\n}\n\nfunction escapeJsonPointer(value: string): string {\n return value.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","/**\n * Reviewed consent copy for the core API integration definitions.\n *\n * Presentation only: nothing here grants a scope, selects a connection, or\n * replaces server-side authorization. The copy used to live hardcoded in the\n * web bundle (`REVIEWED_INTEGRATION_EXPERIENCES`); it is served with the\n * definition now so polishing a consent screen is a data change, not a\n * frontend release. The web keeps its generic fallback for any definition or\n * field missing here. Gmail's reviewed presentation lives on its catalog row\n * instead (`data/catalog/curated.json`): Gmail is a Connector, not one of\n * these API integration definitions.\n *\n * MCP connectors carry the same shape on their curated catalog row\n * (`presentation` in `data/catalog/curated.json` -> importer ->\n * `capability_catalog_items.metadata.presentation`).\n */\n\nexport type IntegrationPresentationIcon = \"calendar\" | \"cloud\" | \"contacts\" | \"files\" | \"mail\";\n\nexport type IntegrationPresentationCopy = {\n readonly providerName?: string;\n readonly icon?: IntegrationPresentationIcon;\n readonly introduction?: string;\n readonly capabilities?: readonly { readonly title: string; readonly description: string }[];\n readonly permissionSummary?: string;\n readonly scopeLabels?: Readonly<\n Record<string, { readonly label: string; readonly description: string }>\n >;\n};\n\nexport const INTEGRATION_DEFINITION_PRESENTATIONS: Readonly<\n Record<string, IntegrationPresentationCopy>\n> = {\n \"google-drive\": {\n providerName: \"Google\",\n icon: \"files\",\n introduction: \"Let agents work with files in the Google Drive account you choose.\",\n capabilities: [\n {\n title: \"Find files and folders\",\n description: \"Browse and search content in My Drive and shared drives.\",\n },\n {\n title: \"Create and update content\",\n description: \"Work with files and folders through the reviewed Drive tools.\",\n },\n {\n title: \"Manage sharing\",\n description: \"Review and update links, permissions, and shared-drive content.\",\n },\n ],\n permissionSummary:\n \"Google asks for access to the Drive account you approve, including files shared with that account.\",\n scopeLabels: {\n \"https://www.googleapis.com/auth/drive\": {\n label: \"Work with Google Drive files\",\n description: \"See, create, edit, organize, and share files available to this account.\",\n },\n },\n },\n \"microsoft-outlook-mail\": {\n providerName: \"Microsoft\",\n icon: \"mail\",\n introduction: \"Let agents work with mail in the Microsoft account you choose.\",\n capabilities: [\n {\n title: \"Find and understand mail\",\n description: \"Search messages, folders, and attachments for useful context.\",\n },\n {\n title: \"Draft and send messages\",\n description: \"Prepare, update, and send mail through the reviewed Outlook tools.\",\n },\n {\n title: \"Manage mailbox settings\",\n description: \"Work with supported folders, classifications, and mailbox preferences.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for mail and mailbox-setting access for the account you approve.\",\n scopeLabels: {\n \"Mail.ReadWrite\": {\n label: \"Read and update mail\",\n description: \"Work with messages, folders, and attachments in this mailbox.\",\n },\n \"Mail.Send\": {\n label: \"Send mail\",\n description: \"Send messages as the connected Microsoft account.\",\n },\n \"MailboxSettings.ReadWrite\": {\n label: \"Manage mailbox settings\",\n description: \"Read and update supported Outlook mailbox preferences.\",\n },\n },\n },\n \"microsoft-outlook-calendar\": {\n providerName: \"Microsoft\",\n icon: \"calendar\",\n introduction: \"Let agents help coordinate the calendars in your Microsoft account.\",\n capabilities: [\n {\n title: \"Understand your schedule\",\n description: \"Review calendars, events, availability, and reminders.\",\n },\n {\n title: \"Plan meetings\",\n description: \"Find suitable times and coordinate calendar activity.\",\n },\n {\n title: \"Manage events\",\n description: \"Create and update events through the reviewed calendar tools.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for permission to view and manage calendars for the account you approve.\",\n scopeLabels: {\n \"Calendars.ReadWrite\": {\n label: \"View and manage calendars\",\n description: \"Read, create, update, and organize calendar events.\",\n },\n },\n },\n \"microsoft-outlook-contacts\": {\n providerName: \"Microsoft\",\n icon: \"contacts\",\n introduction: \"Let agents work with contacts in your Microsoft account.\",\n capabilities: [\n {\n title: \"Find people\",\n description: \"Look up contacts and relevant people suggestions.\",\n },\n {\n title: \"Organize contacts\",\n description: \"Work with contacts and contact folders.\",\n },\n {\n title: \"Keep details current\",\n description: \"Create or update contact information through reviewed tools.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for contact access and people suggestions for the account you approve.\",\n scopeLabels: {\n \"Contacts.ReadWrite\": {\n label: \"View and manage contacts\",\n description: \"Read, create, update, and organize contacts and contact folders.\",\n },\n \"People.Read.All\": {\n label: \"Find relevant people\",\n description: \"Use people suggestions available to the connected account.\",\n },\n },\n },\n \"microsoft-onedrive\": {\n providerName: \"Microsoft\",\n icon: \"cloud\",\n introduction: \"Let agents work with files in the Microsoft account you choose.\",\n capabilities: [\n {\n title: \"Find files and folders\",\n description: \"Browse drives, folders, shared items, and sites available to the account.\",\n },\n {\n title: \"Create and update content\",\n description: \"Work with OneDrive and SharePoint files through reviewed tools.\",\n },\n {\n title: \"Manage sharing\",\n description: \"Review and update sharing links and permissions.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for file and site access anywhere the connected account already has access.\",\n scopeLabels: {\n \"Files.ReadWrite.All\": {\n label: \"Work with accessible files\",\n description: \"Read, create, update, and organize files available to this account.\",\n },\n \"Sites.ReadWrite.All\": {\n label: \"Work with accessible sites\",\n description: \"Read and update files in SharePoint sites available to this account.\",\n },\n },\n },\n};\n"],"mappings":";AA0GO,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YACW,MACT,SACA;AACA,UAAM,OAAO;AAHJ;AAIT,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YACW,MACT,SACS,SACA,WACA,QACT;AACA,UAAM,OAAO;AANJ;AAEA;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AACF;;;AC5HA,IAAM,6BAA6B,oBAAI,IAAI;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,4BAA4B;AAClC,IAAM,6BAA6B;AACnC,IAAM,8BAA8B;AACpC,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAE1B,SAAS,sBAAsB,MAAkC;AAC/D,MAAI,CAAC,MAAM,KAAK,EAAG,QAAO;AAC1B,QAAM,aAAa,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AACzD,SAAO,WAAW,SAAS,GAAG,IAAI,aAAa,GAAG,UAAU;AAC9D;AAEO,SAAS,yBACd,YACA,aACM;AACN,MAAI;AACJ,MAAI;AACF,e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","isRecord","normalizeMcpSchema","isRecord","stringValue"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/auth.ts","../src/graphql.ts","../src/http.ts","../src/revision.ts","../src/mcp-manifest.ts","../src/mcp-bridge.ts","../src/openapi.ts","../src/integration-definitions.ts","../src/integration-presentations.ts"],"sourcesContent":["import type { FetchLike, OutboundNetworkSettings } from \"@opengeni/network\";\n\nexport type IntegrationProtocol = \"mcp\" | \"openapi\" | \"graphql\";\nexport type IntegrationToolSafety = \"read\" | \"write\" | \"destructive\";\nexport type IntegrationApprovalMode = \"never\" | \"ask\";\n\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\nexport interface IntegrationToolDefinition {\n readonly id: string;\n readonly operationKey: string;\n readonly name: string;\n readonly description: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly safety: IntegrationToolSafety;\n readonly approvalMode: IntegrationApprovalMode;\n readonly deprecated: boolean;\n}\n\nexport type CredentialCarrier = \"header\" | \"query\" | \"cookie\";\n\nexport interface IntegrationCredentialPlacement {\n readonly carrier: CredentialCarrier;\n readonly name: string;\n readonly value: string;\n readonly prefix?: string;\n}\n\nexport interface IntegrationCredentialAudience {\n /** Exact normalized origin the credential may reach. */\n readonly origin: string;\n /** Optional normalized path prefix. Defaults to `/`. */\n readonly pathPrefix?: string;\n}\n\nexport interface ResolvedIntegrationCredential {\n readonly audience: IntegrationCredentialAudience;\n readonly placements: readonly IntegrationCredentialPlacement[];\n /** Exact accepted-attempt fence invoked immediately before one HTTP request. */\n readonly authorizeProviderRequest?: () => Promise<boolean>;\n readonly expiresAt?: string;\n readonly scope?: readonly string[];\n}\n\nexport interface IntegrationInvocationAuthority {\n readonly accountId: string;\n readonly workspaceId: string;\n readonly sessionId?: string;\n readonly rootSessionId?: string;\n readonly turnId?: string;\n readonly attemptId?: string;\n readonly initiatingSubjectId?: string;\n readonly connectionRef?: string;\n}\n\nexport interface ResolveIntegrationCredentialRequest extends IntegrationInvocationAuthority {\n readonly protocol: Exclude<IntegrationProtocol, \"mcp\">;\n readonly definitionId: string;\n readonly revisionId: string;\n readonly operationKey: string;\n readonly destinationUrl: string;\n readonly requiredScopeAlternatives?: readonly (readonly string[])[];\n /** Refresh the exact bound Connection for a safe retry or a later call. */\n readonly forceRefresh?: boolean;\n}\n\nexport interface IntegrationCredentialResolver {\n resolve(\n request: ResolveIntegrationCredentialRequest,\n ): Promise<ResolvedIntegrationCredential | null>;\n}\n\nexport interface IntegrationTransport {\n readonly fetch: FetchLike;\n}\n\nexport interface PinnedIntegrationTransportOptions {\n readonly network: OutboundNetworkSettings;\n readonly fetchImpl?: FetchLike;\n}\n\nexport type IntegrationRevisionSource = {\n readonly url?: string;\n readonly provider?: string;\n readonly fetchedAt?: string;\n};\n\nexport interface IntegrationRevision<\n TBinding = unknown,\n TProtocol extends Exclude<IntegrationProtocol, \"mcp\"> = Exclude<IntegrationProtocol, \"mcp\">,\n> {\n readonly id: string;\n readonly protocol: TProtocol;\n readonly definitionId: string;\n readonly contentSha256: string;\n readonly source: IntegrationRevisionSource;\n readonly title: string;\n readonly description?: string;\n readonly version?: string;\n readonly tools: readonly IntegrationToolDefinition[];\n readonly bindings: Readonly<Record<string, TBinding>>;\n}\n\nexport type InvocationOutcome = \"not_started\" | \"unknown\" | \"failed\";\n\nexport class IntegrationProtocolError extends Error {\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"IntegrationProtocolError\";\n }\n}\n\nexport class IntegrationInvocationError extends Error {\n constructor(\n readonly code: string,\n message: string,\n readonly outcome: InvocationOutcome,\n readonly retryable: boolean,\n readonly status?: number,\n ) {\n super(message);\n this.name = \"IntegrationInvocationError\";\n }\n}\n","import type { IntegrationCredentialPlacement, ResolvedIntegrationCredential } from \"./types\";\nimport { IntegrationInvocationError } from \"./types\";\n\nconst forbiddenCredentialHeaders = new Set([\n \"connection\",\n \"content-length\",\n \"host\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\nconst MAX_CREDENTIAL_PLACEMENTS = 32;\nconst MAX_CREDENTIAL_NAME_LENGTH = 256;\nconst MAX_CREDENTIAL_VALUE_LENGTH = 16_384;\nconst headerNamePattern = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;\nconst queryNamePattern = /^[A-Za-z0-9._~-]+$/;\nconst cookieNamePattern = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nfunction normalizeAudiencePath(path: string | undefined): string {\n if (!path?.trim()) return \"/\";\n const normalized = path.startsWith(\"/\") ? path : `/${path}`;\n return normalized.endsWith(\"/\") ? normalized : `${normalized}/`;\n}\n\nexport function assertCredentialAudience(\n credential: ResolvedIntegrationCredential,\n destination: URL,\n): void {\n let audience: URL;\n try {\n audience = new URL(credential.audience.origin);\n } catch {\n throw new IntegrationInvocationError(\n \"credential_audience_invalid\",\n \"Connection credential audience is invalid\",\n \"not_started\",\n false,\n );\n }\n if (\n audience.origin !== destination.origin ||\n audience.username ||\n audience.password ||\n audience.pathname !== \"/\" ||\n audience.search ||\n audience.hash\n ) {\n throw new IntegrationInvocationError(\n \"credential_audience_mismatch\",\n \"Connection credential is not authorized for this integration destination\",\n \"not_started\",\n false,\n );\n }\n const prefix = normalizeAudiencePath(credential.audience.pathPrefix);\n const path = destination.pathname.endsWith(\"/\")\n ? destination.pathname\n : `${destination.pathname}/`;\n if (!path.startsWith(prefix)) {\n throw new IntegrationInvocationError(\n \"credential_path_mismatch\",\n \"Connection credential is not authorized for this integration path\",\n \"not_started\",\n false,\n );\n }\n}\n\nfunction placementValue(placement: IntegrationCredentialPlacement): string {\n return `${placement.prefix ?? \"\"}${placement.value}`;\n}\n\nfunction validateCredentialPlacements(placements: readonly IntegrationCredentialPlacement[]): void {\n if (placements.length === 0 || placements.length > MAX_CREDENTIAL_PLACEMENTS) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placement count is invalid\",\n \"not_started\",\n false,\n );\n }\n const seen = new Set<string>();\n for (const placement of placements) {\n const name = placement.name;\n const value = placementValue(placement);\n const normalizedName = placement.carrier === \"header\" ? name.toLowerCase() : name;\n if (\n name.length === 0 ||\n name.length > MAX_CREDENTIAL_NAME_LENGTH ||\n placement.value.length === 0 ||\n value.length > MAX_CREDENTIAL_VALUE_LENGTH ||\n /[\\r\\n\\0]/.test(name) ||\n /[\\r\\n\\0]/.test(value)\n ) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placement is invalid\",\n \"not_started\",\n false,\n );\n }\n if (placement.carrier === \"header\") {\n if (\n !headerNamePattern.test(name) ||\n forbiddenCredentialHeaders.has(normalizedName) ||\n normalizedName.startsWith(\"sec-\")\n ) {\n throw new IntegrationInvocationError(\n \"credential_header_forbidden\",\n \"Connection credential targets a forbidden request header\",\n \"not_started\",\n false,\n );\n }\n } else if (placement.carrier === \"query\") {\n if (!queryNamePattern.test(name)) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential query placement is invalid\",\n \"not_started\",\n false,\n );\n }\n } else if (!cookieNamePattern.test(name) || /;/.test(value)) {\n throw new IntegrationInvocationError(\n \"credential_cookie_invalid\",\n \"Connection credential cookie placement is invalid\",\n \"not_started\",\n false,\n );\n }\n const key = `${placement.carrier}\\0${normalizedName}`;\n if (seen.has(key)) {\n throw new IntegrationInvocationError(\n \"credential_placement_invalid\",\n \"Connection credential placements contain a duplicate destination\",\n \"not_started\",\n false,\n );\n }\n seen.add(key);\n }\n}\n\nexport function applyCredentialPlacements(\n destination: URL,\n headers: Headers,\n credential: ResolvedIntegrationCredential,\n): void {\n assertCredentialAudience(credential, destination);\n validateCredentialPlacements(credential.placements);\n const cookies: string[] = [];\n for (const placement of credential.placements) {\n const name = placement.name;\n const value = placementValue(placement);\n if (placement.carrier === \"header\") {\n headers.set(name, value);\n } else if (placement.carrier === \"query\") {\n destination.searchParams.set(name, value);\n } else {\n cookies.push(`${name}=${value}`);\n }\n }\n if (cookies.length > 0) {\n const current = headers.get(\"cookie\");\n headers.set(\"cookie\", [...(current ? [current] : []), ...cookies].join(\"; \"));\n }\n}\n","import type { CallToolResultContent, MCPCallToolOptions, MCPServer } from \"@openai/agents\";\nimport {\n buildClientSchema,\n getIntrospectionQuery,\n getNamedType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n parse,\n type GraphQLInputType,\n type GraphQLNamedType,\n type GraphQLOutputType,\n type IntrospectionQuery,\n} from \"graphql\";\n\nimport { applyCredentialPlacements } from \"./auth\";\nimport {\n DEFAULT_INTEGRATION_RESPONSE_BYTES,\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n MAX_INTEGRATION_SPEC_BYTES,\n MAX_INTEGRATION_TOOLS,\n fetchWithDeadline,\n readIntegrationResponse,\n} from \"./http\";\nimport { canonicalJson, immutableRevisionId, sha256Hex, stableToolId } from \"./revision\";\nimport type {\n IntegrationCredentialResolver,\n IntegrationInvocationAuthority,\n IntegrationRevision,\n IntegrationTransport,\n JsonSchema,\n} from \"./types\";\nimport { IntegrationInvocationError, IntegrationProtocolError } from \"./types\";\n\nexport interface GraphqlOperationBinding {\n readonly kind: \"query\" | \"mutation\";\n readonly fieldName: string;\n readonly operationName: string;\n readonly variableDefinitions: readonly string[];\n readonly variableNames: readonly string[];\n readonly defaultSelection?: string;\n readonly selectionAllowed: boolean;\n}\n\nexport type GraphqlRevision = IntegrationRevision<GraphqlOperationBinding, \"graphql\">;\n\nexport interface CompileGraphqlOptions {\n readonly definitionId: string;\n readonly endpoint: string;\n readonly name?: string;\n readonly sourceUrl?: string;\n readonly provider?: string;\n}\n\nexport interface GraphqlServerOptions {\n readonly revision: GraphqlRevision;\n readonly endpoint: string;\n readonly transport: IntegrationTransport;\n readonly credentialResolver?: IntegrationCredentialResolver;\n readonly authority: IntegrationInvocationAuthority;\n readonly staticHeaders?: Readonly<Record<string, string>>;\n readonly staticQuery?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly maxResponseBytes?: number;\n}\n\ntype LocalMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\nexport function compileGraphqlRevision(\n introspection: IntrospectionQuery | { readonly data?: IntrospectionQuery } | string,\n options: CompileGraphqlOptions,\n): GraphqlRevision {\n const document = parseIntrospection(introspection);\n let schema;\n try {\n schema = buildClientSchema(document);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_introspection_invalid\",\n \"GraphQL introspection result cannot build a client schema\",\n );\n }\n const endpoint = validateGraphqlEndpoint(options.endpoint);\n const contentSha256 = sha256Hex(canonicalJson(document));\n const id = immutableRevisionId(\"graphql\", contentSha256);\n const tools = [] as GraphqlRevision[\"tools\"] extends readonly (infer T)[] ? T[] : never;\n const bindings: Record<string, GraphqlOperationBinding> = {};\n const seen = new Map<string, number>();\n\n for (const [kind, root] of [\n [\"query\", schema.getQueryType()],\n [\"mutation\", schema.getMutationType()],\n ] as const) {\n if (!root) continue;\n for (const field of Object.values(root.getFields()).sort((left, right) =>\n left.name.localeCompare(right.name),\n )) {\n const toolId = stableToolId(`${kind}_${field.name}`, seen);\n const namedOutput = getNamedType(field.type);\n const selectionAllowed = !isLeafType(namedOutput);\n const defaultSelection = selectionAllowed\n ? buildDefaultSelection(field.type, new Set(), 0)\n : undefined;\n const properties: Record<string, unknown> = Object.fromEntries(\n field.args.map((arg) => [\n arg.name,\n {\n ...inputTypeSchema(arg.type, new Set(), 0),\n ...(arg.description ? { description: arg.description } : {}),\n },\n ]),\n );\n if (selectionAllowed) {\n properties.select = {\n type: \"string\",\n description:\n \"Optional GraphQL field selection without outer braces. The default selects safe scalar fields.\",\n maxLength: 4_000,\n };\n }\n const required = field.args.filter((arg) => isNonNullType(arg.type)).map((arg) => arg.name);\n const description = [\n field.description?.trim(),\n kind === \"mutation\"\n ? \"Changes external state and requires approval.\"\n : \"Read-only GraphQL query.\",\n ]\n .filter(Boolean)\n .join(\" \");\n tools.push({\n id: toolId,\n operationKey: `${kind}:${field.name}`,\n name: field.name,\n description,\n inputSchema: {\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n },\n safety: kind === \"query\" ? \"read\" : \"write\",\n approvalMode: kind === \"query\" ? \"never\" : \"ask\",\n deprecated: field.deprecationReason != null,\n });\n bindings[toolId] = {\n kind,\n fieldName: field.name,\n operationName: stableGraphqlName(`${kind}_${field.name}`),\n variableDefinitions: field.args.map((arg) => `$${arg.name}: ${String(arg.type)}`),\n variableNames: field.args.map((arg) => arg.name),\n ...(defaultSelection ? { defaultSelection } : {}),\n selectionAllowed,\n };\n if (tools.length > MAX_INTEGRATION_TOOLS) {\n throw new IntegrationProtocolError(\n \"graphql_tool_limit\",\n `GraphQL schema exceeds the ${MAX_INTEGRATION_TOOLS}-tool limit`,\n );\n }\n }\n }\n if (tools.length === 0) {\n throw new IntegrationProtocolError(\"graphql_empty\", \"GraphQL schema exposes no root fields\");\n }\n return {\n id,\n protocol: \"graphql\",\n definitionId: options.definitionId,\n contentSha256,\n source: {\n url: options.sourceUrl ?? endpoint,\n ...(options.provider ? { provider: options.provider } : {}),\n },\n title: options.name?.trim() || options.definitionId,\n tools,\n bindings,\n };\n}\n\nexport async function fetchGraphqlIntrospection(\n options: Omit<GraphqlServerOptions, \"revision\">,\n): Promise<IntrospectionQuery> {\n const request = { query: getIntrospectionQuery({ descriptions: true }) };\n const firstCredential = await resolveGraphqlCredential(\n options,\n \"graphql-introspection\",\n \"pending\",\n \"__introspection\",\n false,\n );\n let response = await sendGraphqlRequest(options, request, firstCredential);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveGraphqlCredential(\n options,\n \"graphql-introspection\",\n \"pending\",\n \"__introspection\",\n true,\n );\n await response.body?.cancel().catch(() => undefined);\n if (!refreshed) {\n throw new IntegrationInvocationError(\n \"graphql_introspection_rejected\",\n \"GraphQL endpoint did not return an introspection schema\",\n \"failed\",\n false,\n 401,\n );\n }\n response = await sendGraphqlRequest(options, request, refreshed);\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"GraphQL endpoint attempted to redirect the introspection request\",\n \"unknown\",\n false,\n response.status,\n );\n }\n const body = await readIntegrationResponse(response, MAX_INTEGRATION_SPEC_BYTES);\n if (!response.ok || !isRecord(body.data) || !isRecord(body.data.data)) {\n throw new IntegrationInvocationError(\n \"graphql_introspection_rejected\",\n \"GraphQL endpoint did not return an introspection schema\",\n \"failed\",\n false,\n response.status,\n );\n }\n return body.data.data as unknown as IntrospectionQuery;\n}\n\nexport class GraphqlMcpServer implements MCPServer {\n readonly cacheToolsList = true;\n readonly useStructuredContent = true;\n readonly name: string;\n\n constructor(private readonly options: GraphqlServerOptions) {\n this.name = `graphql:${stableToolId(options.revision.definitionId)}`;\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n async invalidateToolsCache(): Promise<void> {}\n\n async listTools(): Promise<LocalMcpTool[]> {\n return this.options.revision.tools.map(\n (tool) =>\n ({\n name: tool.id,\n description: tool.description,\n inputSchema: normalizeMcpSchema(tool.inputSchema),\n annotations: {\n readOnlyHint: tool.safety === \"read\",\n destructiveHint: false,\n idempotentHint: tool.safety === \"read\",\n openWorldHint: true,\n },\n _meta: {\n \"opengeni/approvalMode\": tool.approvalMode,\n \"opengeni/operationKey\": tool.operationKey,\n \"opengeni/revisionId\": this.options.revision.id,\n },\n }) as LocalMcpTool,\n );\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n _meta?: Record<string, unknown> | null,\n callOptions?: MCPCallToolOptions,\n ): Promise<CallToolResultContent> {\n const result = await invokeGraphqlOperation(\n this.options,\n toolName,\n args ?? {},\n callOptions?.signal,\n );\n const content = [\n { type: \"text\" as const, text: JSON.stringify(result) },\n ] as CallToolResultContent;\n content.structuredContent = result;\n content.isError = result.ok === false;\n return content;\n }\n}\n\nexport function createGraphqlMcpServer(options: GraphqlServerOptions): MCPServer {\n return new GraphqlMcpServer(options);\n}\n\nexport async function invokeGraphqlOperation(\n options: GraphqlServerOptions,\n toolId: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const binding = options.revision.bindings[toolId];\n if (!binding) {\n throw new IntegrationInvocationError(\n \"operation_not_found\",\n \"GraphQL operation is not present in the frozen revision\",\n \"not_started\",\n false,\n );\n }\n const select = binding.selectionAllowed\n ? validateGraphqlSelection(\n typeof args.select === \"string\" ? args.select : (binding.defaultSelection ?? \"__typename\"),\n )\n : undefined;\n const variables = Object.fromEntries(\n binding.variableNames.flatMap((name) => (args[name] === undefined ? [] : [[name, args[name]]])),\n );\n const definitions = binding.variableDefinitions.length\n ? `(${binding.variableDefinitions.join(\", \")})`\n : \"\";\n const argumentsText = binding.variableNames.length\n ? `(${binding.variableNames.map((name) => `${name}: $${name}`).join(\", \")})`\n : \"\";\n const query = `${binding.kind} ${binding.operationName}${definitions} { ${binding.fieldName}${argumentsText}${select ? ` { ${select} }` : \"\"} }`;\n const request = { query, variables, operationName: binding.operationName };\n const firstCredential = await resolveGraphqlCredential(\n options,\n options.revision.definitionId,\n options.revision.id,\n toolId,\n false,\n );\n let response = await sendGraphqlRequest(options, request, firstCredential, signal);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveGraphqlCredential(\n options,\n options.revision.definitionId,\n options.revision.id,\n toolId,\n true,\n );\n await response.body?.cancel().catch(() => undefined);\n if (binding.kind === \"query\" && refreshed) {\n response = await sendGraphqlRequest(options, request, refreshed, signal);\n } else {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this GraphQL operation\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n 401,\n );\n }\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"GraphQL endpoint attempted to redirect a credential-bearing request\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n response.status,\n );\n }\n const payload = await readIntegrationResponse(\n response,\n options.maxResponseBytes ?? DEFAULT_INTEGRATION_RESPONSE_BYTES,\n );\n if (response.status === 401 || response.status === 403) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this GraphQL operation\",\n binding.kind === \"mutation\" ? \"unknown\" : \"failed\",\n false,\n response.status,\n );\n }\n const graph = isRecord(payload.data) ? payload.data : {};\n return {\n ok: response.ok && !Array.isArray(graph.errors),\n status: response.status,\n data: graph.data ?? null,\n errors: graph.errors ?? null,\n };\n}\n\nasync function resolveGraphqlCredential(\n options: Omit<GraphqlServerOptions, \"revision\"> | GraphqlServerOptions,\n definitionId: string,\n revisionId: string,\n operationKey: string,\n forceRefresh: boolean,\n): Promise<Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>> {\n if (!options.credentialResolver || !options.authority.connectionRef) return null;\n const credential = await options.credentialResolver.resolve({\n ...options.authority,\n protocol: \"graphql\",\n definitionId,\n revisionId,\n operationKey,\n destinationUrl: graphqlEndpoint(options).toString(),\n ...(forceRefresh ? { forceRefresh: true } : {}),\n });\n if (!credential && !forceRefresh) {\n throw new IntegrationInvocationError(\n \"connection_required\",\n \"This GraphQL integration needs a connected account\",\n \"not_started\",\n false,\n );\n }\n return credential;\n}\n\nasync function sendGraphqlRequest(\n options: Omit<GraphqlServerOptions, \"revision\"> | GraphqlServerOptions,\n request: Record<string, unknown>,\n credential: Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>,\n signal?: AbortSignal,\n): Promise<Response> {\n const endpoint = graphqlEndpoint(options);\n const headers = new Headers(options.staticHeaders);\n headers.set(\"accept\", \"application/json\");\n headers.set(\"content-type\", \"application/json\");\n if (credential) applyCredentialPlacements(endpoint, headers, credential);\n if (credential?.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await credential.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n \"not_started\",\n false,\n );\n }\n }\n return await fetchWithDeadline(\n options.transport,\n endpoint,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(request),\n ...(signal ? { signal } : {}),\n },\n options.timeoutMs ?? DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n}\n\nfunction graphqlEndpoint(options: Pick<GraphqlServerOptions, \"endpoint\" | \"staticQuery\">): URL {\n const endpoint = new URL(validateGraphqlEndpoint(options.endpoint));\n for (const [name, value] of Object.entries(options.staticQuery ?? {})) {\n endpoint.searchParams.set(name, value);\n }\n return endpoint;\n}\n\nexport function validateGraphqlSelection(value: string): string {\n const normalized = value.trim();\n if (!normalized || normalized.length > 4_000) {\n throw new IntegrationInvocationError(\n \"graphql_selection_invalid\",\n \"GraphQL selection must contain between 1 and 4000 characters\",\n \"not_started\",\n false,\n );\n }\n try {\n const document = parse(`fragment OpenGeniSelection on Placeholder { ${normalized} }`);\n if (\n document.definitions.length !== 1 ||\n document.definitions[0]?.kind !== \"FragmentDefinition\"\n ) {\n throw new Error(\"invalid selection document\");\n }\n return normalized;\n } catch {\n throw new IntegrationInvocationError(\n \"graphql_selection_invalid\",\n \"GraphQL selection is invalid\",\n \"not_started\",\n false,\n );\n }\n}\n\nfunction parseIntrospection(\n value: IntrospectionQuery | { readonly data?: IntrospectionQuery } | string,\n): IntrospectionQuery {\n let parsed: unknown = value;\n if (typeof value === \"string\") {\n if (Buffer.byteLength(value) > MAX_INTEGRATION_SPEC_BYTES) {\n throw new IntegrationProtocolError(\n \"graphql_introspection_size\",\n `GraphQL introspection exceeds ${MAX_INTEGRATION_SPEC_BYTES} bytes`,\n );\n }\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_introspection_parse\",\n \"GraphQL introspection is not valid JSON\",\n );\n }\n }\n if (isRecord(parsed) && isRecord(parsed.data) && isRecord(parsed.data.__schema)) {\n return parsed.data as unknown as IntrospectionQuery;\n }\n if (isRecord(parsed) && isRecord(parsed.__schema)) {\n return parsed as unknown as IntrospectionQuery;\n }\n throw new IntegrationProtocolError(\n \"graphql_introspection_shape\",\n \"GraphQL introspection result has no __schema object\",\n );\n}\n\nfunction validateGraphqlEndpoint(value: string): string {\n let endpoint: URL;\n try {\n endpoint = new URL(value);\n } catch {\n throw new IntegrationProtocolError(\n \"graphql_endpoint_invalid\",\n \"GraphQL endpoint URL is invalid\",\n );\n }\n if (\n !/^https?:$/.test(endpoint.protocol) ||\n endpoint.username ||\n endpoint.password ||\n endpoint.hash\n ) {\n throw new IntegrationProtocolError(\n \"graphql_endpoint_invalid\",\n \"GraphQL endpoint URL is invalid\",\n );\n }\n return endpoint.toString();\n}\n\nfunction inputTypeSchema(input: GraphQLInputType, seen: Set<string>, depth: number): JsonSchema {\n if (depth > 12) return {};\n if (isNonNullType(input)) return inputTypeSchema(input.ofType, seen, depth + 1);\n if (isListType(input)) {\n return { type: \"array\", items: inputTypeSchema(input.ofType, seen, depth + 1) };\n }\n const type = getNamedType(input);\n if (isScalarType(type)) return scalarSchema(type.name);\n if (isEnumType(type))\n return { type: \"string\", enum: type.getValues().map((entry) => entry.name) };\n if (isInputObjectType(type)) {\n if (seen.has(type.name)) return { type: \"object\", additionalProperties: true };\n const nextSeen = new Set(seen).add(type.name);\n const fields = Object.values(type.getFields());\n return {\n type: \"object\",\n properties: Object.fromEntries(\n fields.map((field) => [\n field.name,\n {\n ...inputTypeSchema(field.type, nextSeen, depth + 1),\n ...(field.description ? { description: field.description } : {}),\n },\n ]),\n ),\n required: fields.filter((field) => isNonNullType(field.type)).map((field) => field.name),\n additionalProperties: false,\n };\n }\n return {};\n}\n\nfunction scalarSchema(name: string): JsonSchema {\n if (name === \"Boolean\") return { type: \"boolean\" };\n if (name === \"Int\") return { type: \"integer\" };\n if (name === \"Float\") return { type: \"number\" };\n if (name === \"ID\" || name === \"String\") return { type: \"string\" };\n return { description: `GraphQL scalar ${name}` };\n}\n\nfunction buildDefaultSelection(\n output: GraphQLOutputType,\n seen: Set<string>,\n depth: number,\n): string | undefined {\n const type = getNamedType(output);\n if (isLeafType(type)) return undefined;\n if (depth > 2 || seen.has(type.name)) return \"__typename\";\n if (isUnionType(type) || isInterfaceType(type)) return \"__typename\";\n if (!isObjectType(type)) return \"__typename\";\n const nextSeen = new Set(seen).add(type.name);\n const fields = Object.values(type.getFields());\n const scalarFields = fields.filter((field) => isLeafType(getNamedType(field.type))).slice(0, 20);\n const selections = scalarFields.map((field) => field.name);\n if (selections.length < 3 && depth < 2) {\n const nested = fields.find(\n (field) => field.args.length === 0 && !isLeafType(getNamedType(field.type)),\n );\n if (nested) {\n const child = buildDefaultSelection(nested.type, nextSeen, depth + 1);\n if (child) selections.push(`${nested.name} { ${child} }`);\n }\n }\n return selections.length ? selections.join(\" \") : \"__typename\";\n}\n\nfunction isLeafType(type: GraphQLNamedType): boolean {\n return isScalarType(type) || isEnumType(type);\n}\n\nfunction stableGraphqlName(value: string): string {\n const normalized = value.replace(/[^_0-9A-Za-z]/g, \"_\").replace(/^([^_A-Za-z])/, \"_$1\");\n return normalized || \"OpenGeniOperation\";\n}\n\nfunction normalizeMcpSchema(schema: JsonSchema): LocalMcpTool[\"inputSchema\"] {\n return {\n type: \"object\",\n properties: isRecord(schema.properties) ? schema.properties : {},\n required: Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [],\n additionalProperties: schema.additionalProperties === true,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { pinnedFetch, readResponseBodyBounded, type FetchLike } from \"@opengeni/network\";\n\nimport type { IntegrationTransport, PinnedIntegrationTransportOptions } from \"./types\";\nimport { IntegrationInvocationError } from \"./types\";\n\nexport const DEFAULT_INTEGRATION_TIMEOUT_MS = 30_000;\nexport const DEFAULT_INTEGRATION_RESPONSE_BYTES = 4 * 1024 * 1024;\nexport const MAX_INTEGRATION_SPEC_BYTES = 8 * 1024 * 1024;\nexport const MAX_CURATED_INTEGRATION_SPEC_BYTES = 64 * 1024 * 1024;\nexport const MAX_INTEGRATION_TOOLS = 2_000;\n\nexport async function fetchIntegrationSourceDocument(\n transport: IntegrationTransport,\n sourceUrl: string,\n maxBytes = MAX_INTEGRATION_SPEC_BYTES,\n): Promise<Uint8Array> {\n const url = new URL(sourceUrl);\n const response = await fetchWithDeadline(\n transport,\n url,\n {\n method: \"GET\",\n headers: { accept: \"application/json, application/yaml, text/yaml, */*;q=0.5\" },\n },\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"source_redirect_rejected\",\n \"Integration source attempted to redirect\",\n \"failed\",\n false,\n response.status,\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"source_fetch_rejected\",\n \"Integration source could not be read\",\n \"failed\",\n response.status >= 500,\n response.status,\n );\n }\n return await readResponseBodyBounded(response, maxBytes, \"Integration source\");\n}\n\nexport function createPinnedIntegrationTransport(\n options: PinnedIntegrationTransportOptions,\n): IntegrationTransport {\n return {\n fetch: (input, init) =>\n pinnedFetch(input, init, options.network, {\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n label: \"Integration request\",\n requireHttpsOutsideLocalTest: true,\n }),\n };\n}\n\nexport function directIntegrationTransport(fetchImpl: FetchLike): IntegrationTransport {\n return { fetch: fetchImpl };\n}\n\nexport async function fetchWithDeadline(\n transport: IntegrationTransport,\n url: URL,\n init: RequestInit,\n timeoutMs = DEFAULT_INTEGRATION_TIMEOUT_MS,\n): Promise<Response> {\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120_000) {\n throw new RangeError(\"integration timeout must be between 1 and 120000 milliseconds\");\n }\n const controller = new AbortController();\n const onAbort = () => controller.abort(init.signal?.reason);\n if (init.signal?.aborted) onAbort();\n else init.signal?.addEventListener(\"abort\", onAbort, { once: true });\n const timer = setTimeout(\n () => controller.abort(new Error(\"integration request timed out\")),\n timeoutMs,\n );\n try {\n return await transport.fetch(url, {\n ...init,\n signal: controller.signal,\n redirect: \"manual\",\n });\n } catch {\n const timedOut = controller.signal.aborted && !init.signal?.aborted;\n throw new IntegrationInvocationError(\n timedOut ? \"request_timeout\" : \"request_failed\",\n timedOut ? \"Integration request timed out\" : \"Integration request failed\",\n requestCouldHaveStarted(init.method) ? \"unknown\" : \"not_started\",\n !requestCouldHaveStarted(init.method),\n );\n } finally {\n clearTimeout(timer);\n init.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction requestCouldHaveStarted(method: string | undefined): boolean {\n const normalized = (method ?? \"GET\").toUpperCase();\n return normalized !== \"GET\" && normalized !== \"HEAD\" && normalized !== \"OPTIONS\";\n}\n\nexport async function readIntegrationResponse(\n response: Response,\n maxBytes = DEFAULT_INTEGRATION_RESPONSE_BYTES,\n): Promise<{ data: unknown; contentType: string; bytes: number }> {\n const body = await readResponseBodyBounded(response, maxBytes, \"Integration response\");\n const contentType =\n response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase() ?? \"\";\n if (body.byteLength === 0) return { data: null, contentType, bytes: 0 };\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(body);\n if (contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n try {\n return { data: JSON.parse(text), contentType, bytes: body.byteLength };\n } catch {\n throw new IntegrationInvocationError(\n \"response_json_invalid\",\n \"Integration returned invalid JSON\",\n \"failed\",\n false,\n response.status,\n );\n }\n }\n return { data: text, contentType, bytes: body.byteLength };\n}\n","import { createHash } from \"node:crypto\";\n\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, canonicalize(entry)]),\n );\n}\n\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(canonicalize(value));\n}\n\nexport function sha256Hex(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function immutableRevisionId(protocol: string, contentSha256: string): string {\n if (!/^[a-f0-9]{64}$/.test(contentSha256)) {\n throw new Error(\"contentSha256 must be a lowercase SHA-256 digest\");\n }\n return `${protocol}:${contentSha256.slice(0, 24)}`;\n}\n\nexport function stableToolId(value: string, seen?: Map<string, number>): string {\n const normalized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, 54);\n const base = normalized || \"tool\";\n if (!seen) return base;\n const count = (seen.get(base) ?? 0) + 1;\n seen.set(base, count);\n return count === 1 ? base : `${base}_${count}`;\n}\n","import { stableToolId } from \"./revision\";\n\nexport interface McpToolManifestEntry {\n readonly toolId: string;\n readonly toolName: string;\n readonly description: string | null;\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n readonly annotations?: Readonly<Record<string, unknown>>;\n}\n\nexport interface McpToolManifest {\n readonly server: {\n readonly name: string | null;\n readonly version: string | null;\n readonly instructions: string | null;\n } | null;\n readonly tools: readonly McpToolManifestEntry[];\n}\n\nexport function extractMcpToolManifest(\n listToolsResult: unknown,\n metadata: {\n readonly serverInfo?: unknown;\n readonly instructions?: string;\n } = {},\n): McpToolManifest {\n const listed =\n listToolsResult &&\n typeof listToolsResult === \"object\" &&\n Array.isArray((listToolsResult as { tools?: unknown }).tools)\n ? (listToolsResult as { tools: unknown[] }).tools\n : [];\n const seen = new Map<string, number>();\n const tools = listed.flatMap((value): McpToolManifestEntry[] => {\n if (!value || typeof value !== \"object\") return [];\n const tool = value as Record<string, unknown>;\n if (typeof tool.name !== \"string\" || !tool.name.trim()) return [];\n const toolName = tool.name.trim();\n return [\n {\n toolId: stableToolId(toolName, seen),\n toolName,\n description: typeof tool.description === \"string\" ? tool.description : null,\n ...(tool.inputSchema !== undefined\n ? { inputSchema: tool.inputSchema }\n : tool.parameters !== undefined\n ? { inputSchema: tool.parameters }\n : {}),\n ...(tool.outputSchema !== undefined ? { outputSchema: tool.outputSchema } : {}),\n ...(tool.annotations && typeof tool.annotations === \"object\"\n ? { annotations: tool.annotations as Readonly<Record<string, unknown>> }\n : {}),\n },\n ];\n });\n const info =\n metadata.serverInfo && typeof metadata.serverInfo === \"object\"\n ? (metadata.serverInfo as Record<string, unknown>)\n : null;\n return {\n server: info\n ? {\n name: typeof info.name === \"string\" ? info.name : null,\n version: typeof info.version === \"string\" ? info.version : null,\n instructions: metadata.instructions ?? null,\n }\n : null,\n tools,\n };\n}\n\nexport function deriveMcpNamespace(input: {\n readonly name?: string | null;\n readonly endpoint?: string | null;\n readonly command?: string | null;\n}): string {\n const candidate =\n input.name?.trim() || hostname(input.endpoint) || basename(input.command) || \"mcp\";\n return stableToolId(candidate);\n}\n\nfunction hostname(value: string | null | undefined): string {\n if (!value || !URL.canParse(value)) return \"\";\n return new URL(value).hostname;\n}\n\nfunction basename(value: string | null | undefined): string {\n return value?.trim().split(/[\\\\/]/).pop() ?? \"\";\n}\n","import type { MCPServer } from \"@openai/agents\";\n\nexport const LOCAL_MCP_BRIDGE_CONTRACT_VERSION = 1 as const;\n\nexport type LocalMcpBridgeAuthority = \"connection\" | \"host\" | \"none\";\nexport type LocalMcpBridgeToolSurface = \"static_reviewed\";\n\nexport type LocalMcpBridgeDestination = Readonly<{\n origin: string;\n pathPrefix: string;\n}>;\n\n/**\n * Secret-free description of an in-process provider-to-MCP adapter.\n *\n * This is observability and registration metadata, not authorization. The\n * adapter must still revalidate its named authority before each physical\n * provider request and keep credentials outside tool results and schemas.\n */\nexport type LocalMcpBridgeDescriptor = Readonly<{\n contractVersion: typeof LOCAL_MCP_BRIDGE_CONTRACT_VERSION;\n adapterId: string;\n providerId: string;\n catalogIdentity: string;\n transport: \"in_process\";\n authority: LocalMcpBridgeAuthority;\n toolSurface: LocalMcpBridgeToolSurface;\n mutationReplay: \"safe_reads_only\";\n destinations: readonly LocalMcpBridgeDestination[];\n}>;\n\nexport interface LocalMcpBridgeServer extends MCPServer {\n readonly bridge: LocalMcpBridgeDescriptor;\n}\n\nexport interface LocalMcpBridgeAdapter<TConfig, TContext> {\n readonly adapterId: string;\n matches(config: TConfig): boolean;\n create(config: TConfig, context: TContext): LocalMcpBridgeServer;\n}\n\nexport function defineLocalMcpBridgeDescriptor(\n input: Omit<LocalMcpBridgeDescriptor, \"contractVersion\" | \"transport\">,\n): LocalMcpBridgeDescriptor {\n const adapterId = boundedIdentity(input.adapterId, \"adapterId\");\n const providerId = boundedIdentity(input.providerId, \"providerId\");\n const catalogIdentity = boundedIdentity(input.catalogIdentity, \"catalogIdentity\", 512);\n if (input.destinations.length === 0 || input.destinations.length > 32) {\n throw new Error(\"Local MCP bridge must declare 1-32 provider destinations\");\n }\n const destinations = input.destinations.map((destination) => {\n const url = new URL(destination.origin);\n if (url.protocol !== \"https:\" || url.origin !== destination.origin) {\n throw new Error(\"Local MCP bridge destinations must be exact HTTPS origins\");\n }\n if (\n !destination.pathPrefix.startsWith(\"/\") ||\n destination.pathPrefix.includes(\"\\\\\") ||\n destination.pathPrefix.includes(\"?\") ||\n destination.pathPrefix.includes(\"#\") ||\n new URL(destination.pathPrefix, url.origin).pathname !== destination.pathPrefix\n ) {\n throw new Error(\"Local MCP bridge destination pathPrefix must be an absolute URL path\");\n }\n return Object.freeze({ origin: url.origin, pathPrefix: destination.pathPrefix });\n });\n return Object.freeze({\n contractVersion: LOCAL_MCP_BRIDGE_CONTRACT_VERSION,\n adapterId,\n providerId,\n catalogIdentity,\n transport: \"in_process\",\n authority: input.authority,\n toolSurface: input.toolSurface,\n mutationReplay: input.mutationReplay,\n destinations: Object.freeze(destinations),\n });\n}\n\nexport function isLocalMcpBridgeServer(server: MCPServer): server is LocalMcpBridgeServer {\n const bridge = (server as Partial<LocalMcpBridgeServer>).bridge;\n return (\n bridge?.contractVersion === LOCAL_MCP_BRIDGE_CONTRACT_VERSION &&\n bridge.transport === \"in_process\"\n );\n}\n\n/**\n * Select exactly one adapter for a runtime catalog row. Ambiguous matches fail\n * closed so adding a bridge cannot silently replace another provider route.\n */\nexport function createLocalMcpBridgeFromAdapters<TConfig, TContext>(\n adapters: readonly LocalMcpBridgeAdapter<TConfig, TContext>[],\n config: TConfig,\n context: TContext,\n): LocalMcpBridgeServer | null {\n const matches = adapters.filter((adapter) => adapter.matches(config));\n if (matches.length === 0) return null;\n if (matches.length > 1) {\n throw new Error(\n `Multiple local MCP bridge adapters matched: ${matches.map((entry) => entry.adapterId).join(\", \")}`,\n );\n }\n const adapter = matches[0]!;\n const server = adapter.create(config, context);\n if (server.bridge.adapterId !== adapter.adapterId) {\n throw new Error(`Local MCP bridge adapter ${adapter.adapterId} returned mismatched metadata`);\n }\n return server;\n}\n\nfunction boundedIdentity(value: string, name: string, max = 128): string {\n if (value.length === 0 || value.length > max || /[\\u0000-\\u001f\\u007f]/u.test(value)) {\n throw new Error(`Local MCP bridge ${name} is invalid`);\n }\n return value;\n}\n","import type { CallToolResultContent, MCPCallToolOptions, MCPServer } from \"@openai/agents\";\nimport { load as parseYaml } from \"js-yaml\";\n\nimport { applyCredentialPlacements } from \"./auth\";\nimport {\n DEFAULT_INTEGRATION_RESPONSE_BYTES,\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n MAX_INTEGRATION_SPEC_BYTES,\n MAX_CURATED_INTEGRATION_SPEC_BYTES,\n MAX_INTEGRATION_TOOLS,\n fetchWithDeadline,\n readIntegrationResponse,\n} from \"./http\";\nimport { canonicalJson, immutableRevisionId, sha256Hex, stableToolId } from \"./revision\";\nimport type {\n IntegrationCredentialResolver,\n IntegrationInvocationAuthority,\n IntegrationRevision,\n IntegrationToolDefinition,\n IntegrationTransport,\n JsonSchema,\n} from \"./types\";\nimport { IntegrationInvocationError, IntegrationProtocolError } from \"./types\";\n\nexport type OpenApiHttpMethod =\n | \"get\"\n | \"put\"\n | \"post\"\n | \"delete\"\n | \"patch\"\n | \"head\"\n | \"options\"\n | \"trace\";\n\nexport interface OpenApiParameterBinding {\n readonly name: string;\n readonly location: \"path\" | \"query\" | \"header\" | \"cookie\";\n readonly required: boolean;\n readonly schema: JsonSchema;\n readonly description?: string;\n}\n\nexport interface OpenApiOperationBinding {\n readonly method: OpenApiHttpMethod;\n readonly pathTemplate: string;\n readonly serverUrl: string;\n readonly parameters: readonly OpenApiParameterBinding[];\n readonly requestBody?: {\n readonly required: boolean;\n readonly contentTypes: readonly string[];\n readonly schemas: Readonly<Record<string, JsonSchema>>;\n };\n readonly requiredScopeAlternatives?: readonly (readonly string[])[];\n}\n\nexport type OpenApiRevision = IntegrationRevision<OpenApiOperationBinding, \"openapi\">;\n\nexport interface CompileOpenApiOptions {\n readonly definitionId: string;\n readonly sourceUrl?: string;\n readonly baseUrl?: string;\n readonly provider?: string;\n readonly schemaMode?: \"provider_validated_json\";\n}\n\nexport interface OpenApiServerOptions {\n readonly revision: OpenApiRevision;\n readonly transport: IntegrationTransport;\n readonly credentialResolver?: IntegrationCredentialResolver;\n readonly authority: IntegrationInvocationAuthority;\n readonly timeoutMs?: number;\n readonly maxResponseBytes?: number;\n}\n\nexport type OpenApiAuthDiscovery =\n | { kind: \"none\" }\n | {\n kind: \"oauth2\";\n scopes: string[];\n }\n | {\n kind: \"api_key\";\n carrier: \"header\" | \"query\" | \"cookie\";\n name: string;\n }\n | { kind: \"http\"; scheme: string };\n\ntype LocalMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\nconst methods = new Set<OpenApiHttpMethod>([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nconst forbiddenParameterHeaders = new Set([\n \"host\",\n \"content-length\",\n \"connection\",\n \"transfer-encoding\",\n]);\n\nexport function parseOpenApiDocument(\n source: string | Uint8Array,\n options: { maxBytes?: number } = {},\n): Record<string, unknown> {\n const maxBytes = options.maxBytes ?? MAX_INTEGRATION_SPEC_BYTES;\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n maxBytes > MAX_CURATED_INTEGRATION_SPEC_BYTES\n ) {\n throw new RangeError(\n `OpenAPI parser limit must be between 1 and ${MAX_CURATED_INTEGRATION_SPEC_BYTES} bytes`,\n );\n }\n const bytes = typeof source === \"string\" ? Buffer.byteLength(source) : source.byteLength;\n if (bytes === 0 || bytes > maxBytes) {\n throw new IntegrationProtocolError(\n \"openapi_spec_size\",\n `OpenAPI document must be between 1 and ${maxBytes} bytes`,\n );\n }\n const text =\n typeof source === \"string\" ? source : new TextDecoder(\"utf-8\", { fatal: true }).decode(source);\n let parsed: unknown;\n try {\n parsed = parseYaml(text, { json: true });\n } catch {\n throw new IntegrationProtocolError(\n \"openapi_parse\",\n \"OpenAPI document is not valid JSON or YAML\",\n );\n }\n if (\n !isRecord(parsed) ||\n typeof parsed.openapi !== \"string\" ||\n !/^3\\.(?:0|1)(?:\\.|$)/.test(parsed.openapi)\n ) {\n throw new IntegrationProtocolError(\n \"openapi_version\",\n \"Only OpenAPI 3.0 and 3.1 documents are supported\",\n );\n }\n if (!isRecord(parsed.paths)) {\n throw new IntegrationProtocolError(\"openapi_paths\", \"OpenAPI document has no paths object\");\n }\n return parsed;\n}\n\nexport function compileOpenApiRevision(\n source: string | Uint8Array | Record<string, unknown>,\n options: CompileOpenApiOptions,\n): OpenApiRevision {\n const document = isRecord(source) ? source : parseOpenApiDocument(source);\n const contentSha256 = sha256Hex(\n canonicalJson(options.schemaMode ? { document, schemaMode: options.schemaMode } : document),\n );\n const revisionId = immutableRevisionId(\"openapi\", contentSha256);\n const info = isRecord(document.info) ? document.info : {};\n const documentServers = readServers(document.servers, options.baseUrl, options.sourceUrl);\n const documentSecurity = readSecurity(document.security);\n const tools: IntegrationToolDefinition[] = [];\n const bindings: Record<string, OpenApiOperationBinding> = {};\n const seen = new Map<string, number>();\n\n for (const [pathTemplate, rawPathItem] of Object.entries(\n document.paths as Record<string, unknown>,\n )) {\n const pathItem = resolveObject(document, rawPathItem, \"path item\");\n const sharedParameters = readParameters(document, pathItem.parameters);\n const pathServers = readServers(pathItem.servers, undefined, undefined);\n for (const [rawMethod, rawOperation] of Object.entries(pathItem)) {\n const method = rawMethod.toLowerCase() as OpenApiHttpMethod;\n if (!methods.has(method) || !isRecord(rawOperation)) continue;\n const operation = resolveObject(document, rawOperation, \"operation\");\n const operationKey = operationIdentity(method, pathTemplate, operation.operationId);\n const id = stableToolId(operationKey, seen);\n const parameters = mergeParameters(\n sharedParameters,\n readParameters(document, operation.parameters),\n );\n const requestBody = readRequestBody(document, operation.requestBody, options.schemaMode);\n const serverUrl = firstServerUrl(\n readServers(operation.servers, undefined, undefined),\n pathServers,\n documentServers,\n );\n const requiredScopeAlternatives =\n operation.security === undefined ? documentSecurity : readSecurity(operation.security);\n const safety = classifyHttpSafety(method, operation);\n const inputSchema = operationInputSchema(parameters, requestBody);\n const outputSchema = options.schemaMode\n ? undefined\n : operationOutputSchema(document, operation.responses);\n const summary = stringValue(operation.summary) ?? stringValue(operation.description);\n tools.push({\n id,\n operationKey,\n name: summary ?? `${method.toUpperCase()} ${pathTemplate}`,\n description: toolDescription(method, pathTemplate, operation, safety),\n inputSchema,\n ...(outputSchema ? { outputSchema } : {}),\n safety,\n approvalMode: safety === \"read\" ? \"never\" : \"ask\",\n deprecated: operation.deprecated === true,\n });\n bindings[id] = {\n method,\n pathTemplate,\n serverUrl,\n parameters,\n ...(requestBody ? { requestBody } : {}),\n ...(requiredScopeAlternatives.length > 0 ? { requiredScopeAlternatives } : {}),\n };\n if (tools.length > MAX_INTEGRATION_TOOLS) {\n throw new IntegrationProtocolError(\n \"openapi_tool_limit\",\n `OpenAPI document exceeds the ${MAX_INTEGRATION_TOOLS}-tool limit`,\n );\n }\n }\n }\n if (tools.length === 0) {\n throw new IntegrationProtocolError(\"openapi_empty\", \"OpenAPI document exposes no operations\");\n }\n return {\n id: revisionId,\n protocol: \"openapi\",\n definitionId: options.definitionId,\n contentSha256,\n source: {\n ...(options.sourceUrl ? { url: options.sourceUrl } : {}),\n ...(options.provider ? { provider: options.provider } : {}),\n },\n title: stringValue(info.title) ?? options.definitionId,\n ...(stringValue(info.description) ? { description: stringValue(info.description)! } : {}),\n ...(stringValue(info.version) ? { version: stringValue(info.version)! } : {}),\n tools,\n bindings,\n };\n}\n\nexport function discoverOpenApiAuth(document: Record<string, unknown>): OpenApiAuthDiscovery {\n const components = isRecord(document.components) ? document.components : {};\n const schemes = isRecord(components.securitySchemes) ? components.securitySchemes : {};\n for (const raw of Object.values(schemes)) {\n const scheme = resolveObject(document, raw, \"security scheme\");\n if (scheme.type === \"oauth2\") {\n const flows = isRecord(scheme.flows) ? scheme.flows : {};\n const scopes = new Set<string>();\n for (const flow of Object.values(flows)) {\n if (!isRecord(flow) || !isRecord(flow.scopes)) continue;\n for (const scope of Object.keys(flow.scopes)) scopes.add(scope);\n }\n return { kind: \"oauth2\", scopes: [...scopes].sort() };\n }\n if (\n scheme.type === \"apiKey\" &&\n (scheme.in === \"header\" || scheme.in === \"query\" || scheme.in === \"cookie\") &&\n typeof scheme.name === \"string\" &&\n scheme.name.length > 0\n ) {\n return { kind: \"api_key\", carrier: scheme.in, name: scheme.name };\n }\n if (scheme.type === \"http\" && typeof scheme.scheme === \"string\") {\n return { kind: \"http\", scheme: scheme.scheme.toLowerCase() };\n }\n }\n return { kind: \"none\" };\n}\n\nexport class OpenApiMcpServer implements MCPServer {\n readonly cacheToolsList = true;\n readonly useStructuredContent = true;\n readonly name: string;\n\n constructor(private readonly options: OpenApiServerOptions) {\n this.name = `openapi:${stableToolId(options.revision.definitionId)}`;\n }\n\n async connect(): Promise<void> {}\n async close(): Promise<void> {}\n async invalidateToolsCache(): Promise<void> {}\n\n async listTools(): Promise<LocalMcpTool[]> {\n return this.options.revision.tools.map(\n (tool) =>\n ({\n name: tool.id,\n description: tool.description,\n inputSchema: normalizeMcpSchema(tool.inputSchema),\n annotations: {\n readOnlyHint: tool.safety === \"read\",\n destructiveHint: tool.safety === \"destructive\",\n idempotentHint: isIdempotentMethod(this.options.revision.bindings[tool.id]?.method),\n openWorldHint: true,\n },\n _meta: {\n \"opengeni/approvalMode\": tool.approvalMode,\n \"opengeni/operationKey\": tool.operationKey,\n \"opengeni/revisionId\": this.options.revision.id,\n },\n }) as LocalMcpTool,\n );\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n _meta?: Record<string, unknown> | null,\n callOptions?: MCPCallToolOptions,\n ): Promise<CallToolResultContent> {\n const result = await invokeOpenApiOperation(\n this.options,\n toolName,\n args ?? {},\n callOptions?.signal,\n );\n const content = [\n {\n type: \"text\" as const,\n text: JSON.stringify(result),\n },\n ] as CallToolResultContent;\n content.structuredContent = result as Record<string, unknown>;\n content.isError = result.ok === false;\n return content;\n }\n}\n\nexport function createOpenApiMcpServer(options: OpenApiServerOptions): MCPServer {\n return new OpenApiMcpServer(options);\n}\n\nexport async function invokeOpenApiOperation(\n options: OpenApiServerOptions,\n toolId: string,\n args: Record<string, unknown>,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const binding = options.revision.bindings[toolId];\n if (!binding) {\n throw new IntegrationInvocationError(\n \"operation_not_found\",\n \"Integration operation is not present in the frozen revision\",\n \"not_started\",\n false,\n );\n }\n const firstCredential = await resolveOpenApiCredential(options, binding, toolId, args, false);\n let response = await sendOpenApiRequest(options, binding, args, firstCredential, signal);\n if (response.status === 401 && options.credentialResolver && options.authority.connectionRef) {\n const refreshed = await resolveOpenApiCredential(options, binding, toolId, args, true);\n if (isReplaySafeMethod(binding.method) && refreshed) {\n await response.body?.cancel().catch(() => undefined);\n response = await sendOpenApiRequest(options, binding, args, refreshed, signal);\n } else {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n isReplaySafeMethod(binding.method) ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n }\n if (response.status >= 300 && response.status < 400) {\n await response.body?.cancel().catch(() => undefined);\n throw new IntegrationInvocationError(\n \"redirect_rejected\",\n \"Integration attempted to redirect a credential-bearing request\",\n binding.method === \"get\" || binding.method === \"head\" ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n const payload = await readIntegrationResponse(\n response,\n options.maxResponseBytes ?? DEFAULT_INTEGRATION_RESPONSE_BYTES,\n );\n const result = {\n ok: response.ok,\n status: response.status,\n contentType: payload.contentType,\n data: payload.data,\n };\n if (!response.ok && (response.status === 401 || response.status === 403)) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n binding.method === \"get\" || binding.method === \"head\" ? \"failed\" : \"unknown\",\n false,\n response.status,\n );\n }\n return result;\n}\n\nasync function resolveOpenApiCredential(\n options: OpenApiServerOptions,\n binding: OpenApiOperationBinding,\n toolId: string,\n args: Record<string, unknown>,\n forceRefresh: boolean,\n): Promise<Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>> {\n if (!options.credentialResolver || !options.authority.connectionRef) return null;\n const destinationUrl = buildOperationUrl(binding, args).toString();\n const credential = await options.credentialResolver.resolve({\n ...options.authority,\n protocol: \"openapi\",\n definitionId: options.revision.definitionId,\n revisionId: options.revision.id,\n operationKey: toolId,\n destinationUrl,\n ...(binding.requiredScopeAlternatives\n ? { requiredScopeAlternatives: binding.requiredScopeAlternatives }\n : {}),\n ...(forceRefresh ? { forceRefresh: true } : {}),\n });\n if (!credential && !forceRefresh) {\n throw new IntegrationInvocationError(\n \"connection_required\",\n \"This integration needs a connected account\",\n \"not_started\",\n false,\n );\n }\n return credential;\n}\n\nasync function sendOpenApiRequest(\n options: OpenApiServerOptions,\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n credential: Awaited<ReturnType<IntegrationCredentialResolver[\"resolve\"]>>,\n signal?: AbortSignal,\n): Promise<Response> {\n const url = buildOperationUrl(binding, args);\n const headers = buildOperationHeaders(binding, args);\n const body = buildOperationBody(binding, args, headers);\n if (credential) applyCredentialPlacements(url, headers, credential);\n if (credential?.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await credential.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) {\n throw new IntegrationInvocationError(\n \"authorization_rejected\",\n \"The connected account is no longer authorized for this operation\",\n \"not_started\",\n false,\n );\n }\n }\n return await fetchWithDeadline(\n options.transport,\n url,\n {\n method: binding.method.toUpperCase(),\n headers,\n ...(body !== undefined ? { body } : {}),\n ...(signal ? { signal } : {}),\n },\n options.timeoutMs ?? DEFAULT_INTEGRATION_TIMEOUT_MS,\n );\n}\n\nfunction readServers(\n value: unknown,\n explicitBaseUrl: string | undefined,\n sourceUrl: string | undefined,\n): string[] {\n if (explicitBaseUrl) return [normalizeServerUrl(explicitBaseUrl)];\n const servers = Array.isArray(value)\n ? value.flatMap((entry): string[] =>\n isRecord(entry) && typeof entry.url === \"string\"\n ? [resolveServerUrl(entry.url, sourceUrl)]\n : [],\n )\n : [];\n if (servers.length > 0) return servers;\n if (sourceUrl && URL.canParse(sourceUrl)) {\n const source = new URL(sourceUrl);\n return [`${source.origin}/`];\n }\n return [];\n}\n\nfunction firstServerUrl(...groups: readonly string[][]): string {\n const server = groups.flat().find(Boolean);\n if (!server) {\n throw new IntegrationProtocolError(\n \"openapi_server_missing\",\n \"OpenAPI operation has no resolvable server URL\",\n );\n }\n return server;\n}\n\nfunction resolveServerUrl(value: string, sourceUrl?: string): string {\n if (/[{}]/.test(value)) {\n throw new IntegrationProtocolError(\n \"openapi_server_variable\",\n \"OpenAPI server variables require an explicit resolved base URL\",\n );\n }\n try {\n return normalizeServerUrl(sourceUrl ? new URL(value, sourceUrl).toString() : value);\n } catch {\n throw new IntegrationProtocolError(\"openapi_server_invalid\", \"OpenAPI server URL is invalid\");\n }\n}\n\nfunction normalizeServerUrl(value: string): string {\n const url = new URL(value);\n if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.hash) {\n throw new IntegrationProtocolError(\"openapi_server_invalid\", \"OpenAPI server URL is invalid\");\n }\n return url.toString();\n}\n\nfunction readParameters(\n document: Record<string, unknown>,\n value: unknown,\n): OpenApiParameterBinding[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((raw): OpenApiParameterBinding[] => {\n const parameter = resolveObject(document, raw, \"parameter\");\n const location = parameter.in;\n if (\n typeof parameter.name !== \"string\" ||\n (location !== \"path\" &&\n location !== \"query\" &&\n location !== \"header\" &&\n location !== \"cookie\")\n ) {\n return [];\n }\n if (location === \"header\" && forbiddenParameterHeaders.has(parameter.name.toLowerCase()))\n return [];\n return [\n {\n name: parameter.name,\n location,\n required: location === \"path\" || parameter.required === true,\n schema: dereferenceSchema(document, parameter.schema),\n ...(stringValue(parameter.description)\n ? { description: stringValue(parameter.description)! }\n : {}),\n },\n ];\n });\n}\n\nfunction mergeParameters(\n base: readonly OpenApiParameterBinding[],\n override: readonly OpenApiParameterBinding[],\n): OpenApiParameterBinding[] {\n const merged = new Map(base.map((entry) => [`${entry.location}:${entry.name}`, entry]));\n for (const entry of override) merged.set(`${entry.location}:${entry.name}`, entry);\n return [...merged.values()];\n}\n\nfunction readRequestBody(\n document: Record<string, unknown>,\n value: unknown,\n schemaMode?: CompileOpenApiOptions[\"schemaMode\"],\n): OpenApiOperationBinding[\"requestBody\"] | undefined {\n if (value === undefined) return undefined;\n const body = resolveObject(document, value, \"request body\");\n if (!isRecord(body.content)) return undefined;\n const schemas: Record<string, JsonSchema> = {};\n for (const [contentType, rawMedia] of Object.entries(body.content)) {\n if (!isRecord(rawMedia)) continue;\n const normalizedType = contentType.toLowerCase();\n const jsonBody = normalizedType === \"application/json\" || normalizedType.endsWith(\"+json\");\n schemas[normalizedType] =\n schemaMode === \"provider_validated_json\" && jsonBody\n ? {\n description:\n \"Request JSON for this API operation. The provider validates fields; follow the operation documentation.\",\n }\n : dereferenceSchema(document, rawMedia.schema);\n }\n const contentTypes = Object.keys(schemas);\n return contentTypes.length === 0\n ? undefined\n : { required: body.required === true, contentTypes, schemas };\n}\n\nfunction operationInputSchema(\n parameters: readonly OpenApiParameterBinding[],\n body: OpenApiOperationBinding[\"requestBody\"],\n): JsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const location of [\"path\", \"query\", \"header\", \"cookie\"] as const) {\n const group = parameters.filter((entry) => entry.location === location);\n if (group.length === 0) continue;\n properties[location] = {\n type: \"object\",\n properties: Object.fromEntries(\n group.map((entry) => [\n entry.name,\n { ...entry.schema, ...(entry.description ? { description: entry.description } : {}) },\n ]),\n ),\n required: group.filter((entry) => entry.required).map((entry) => entry.name),\n additionalProperties: false,\n };\n if (group.some((entry) => entry.required)) required.push(location);\n }\n if (body) {\n properties.body = body.schemas[body.contentTypes[0]!] ?? {};\n if (body.contentTypes.length > 1) {\n properties.contentType = { type: \"string\", enum: body.contentTypes };\n }\n if (body.required) required.push(\"body\");\n }\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\nfunction operationOutputSchema(\n document: Record<string, unknown>,\n value: unknown,\n): JsonSchema | undefined {\n if (!isRecord(value)) return undefined;\n for (const status of [\"200\", \"201\", \"202\", \"203\", \"204\", \"default\"]) {\n if (!(status in value)) continue;\n const response = resolveObject(document, value[status], \"response\");\n if (!isRecord(response.content)) return undefined;\n for (const media of Object.values(response.content)) {\n if (isRecord(media) && media.schema !== undefined) {\n return dereferenceSchema(document, media.schema);\n }\n }\n }\n return undefined;\n}\n\nfunction readSecurity(value: unknown): readonly (readonly string[])[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((entry): string[][] => {\n if (!isRecord(entry)) return [];\n const scopes = Object.values(entry).flatMap((raw) =>\n Array.isArray(raw) ? raw.filter((scope): scope is string => typeof scope === \"string\") : [],\n );\n return scopes.length > 0 ? [[...new Set(scopes)].sort()] : [];\n });\n}\n\nfunction classifyHttpSafety(\n method: OpenApiHttpMethod,\n operation: Record<string, unknown>,\n): IntegrationToolDefinition[\"safety\"] {\n if (method === \"get\" || method === \"head\" || method === \"options\") return \"read\";\n const text =\n `${stringValue(operation.operationId) ?? \"\"} ${stringValue(operation.summary) ?? \"\"}`.toLowerCase();\n return method === \"delete\" || /\\b(delete|destroy|remove|revoke|cancel|purge)\\b/.test(text)\n ? \"destructive\"\n : \"write\";\n}\n\nfunction operationIdentity(method: OpenApiHttpMethod, path: string, operationId: unknown): string {\n return typeof operationId === \"string\" && operationId.trim()\n ? operationId.trim()\n : `${method}_${path}`;\n}\n\nfunction toolDescription(\n method: OpenApiHttpMethod,\n path: string,\n operation: Record<string, unknown>,\n safety: IntegrationToolDefinition[\"safety\"],\n): string {\n const description = stringValue(operation.description) ?? stringValue(operation.summary);\n const approval =\n safety === \"read\" ? \"Read-only.\" : \"Changes external state and requires approval.\";\n return `${description ? `${description.trim()} ` : \"\"}${method.toUpperCase()} ${path}. ${approval}`.trim();\n}\n\nfunction isIdempotentMethod(method: OpenApiHttpMethod | undefined): boolean {\n return (\n method === \"get\" ||\n method === \"head\" ||\n method === \"options\" ||\n method === \"put\" ||\n method === \"delete\"\n );\n}\n\nfunction isReplaySafeMethod(method: OpenApiHttpMethod): boolean {\n return method === \"get\" || method === \"head\" || method === \"options\";\n}\n\nfunction buildOperationUrl(binding: OpenApiOperationBinding, args: Record<string, unknown>): URL {\n const pathArgs = objectValue(args.path);\n const path = binding.pathTemplate.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n const value = pathArgs[name];\n if (value === undefined || value === null) {\n throw new IntegrationInvocationError(\n \"path_parameter_missing\",\n \"A required integration path parameter is missing\",\n \"not_started\",\n false,\n );\n }\n return encodeURIComponent(scalarString(value));\n });\n const base = new URL(binding.serverUrl);\n const url = new URL(\n path.replace(/^\\//, \"\"),\n base.toString().endsWith(\"/\") ? base : new URL(`${base}/`),\n );\n const query = objectValue(args.query);\n for (const [name, value] of Object.entries(query)) appendQueryValue(url, name, value);\n return url;\n}\n\nfunction buildOperationHeaders(\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n): Headers {\n const headers = new Headers({ accept: \"application/json, text/plain;q=0.9, */*;q=0.5\" });\n for (const [name, value] of Object.entries(objectValue(args.header))) {\n if (forbiddenParameterHeaders.has(name.toLowerCase())) continue;\n headers.set(name, scalarString(value));\n }\n const cookies = Object.entries(objectValue(args.cookie)).map(\n ([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(scalarString(value))}`,\n );\n if (cookies.length > 0) headers.set(\"cookie\", cookies.join(\"; \"));\n if (binding.requestBody && args.body !== undefined) {\n const requested =\n typeof args.contentType === \"string\" ? args.contentType.toLowerCase() : undefined;\n const contentType =\n requested && binding.requestBody.contentTypes.includes(requested)\n ? requested\n : binding.requestBody.contentTypes[0]!;\n headers.set(\"content-type\", contentType);\n }\n return headers;\n}\n\nfunction buildOperationBody(\n binding: OpenApiOperationBinding,\n args: Record<string, unknown>,\n headers: Headers,\n): BodyInit | undefined {\n if (!binding.requestBody || args.body === undefined) return undefined;\n const contentType = headers.get(\"content-type\") ?? \"application/json\";\n if (contentType === \"application/x-www-form-urlencoded\") {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(objectValue(args.body)))\n appendSearchParam(params, key, value);\n return params;\n }\n if (contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n return JSON.stringify(args.body);\n }\n if (typeof args.body === \"string\") return args.body;\n throw new IntegrationInvocationError(\n \"request_body_unsupported\",\n \"This operation requires a text body for the selected content type\",\n \"not_started\",\n false,\n );\n}\n\nfunction appendQueryValue(url: URL, name: string, value: unknown): void {\n if (Array.isArray(value)) {\n for (const entry of value) url.searchParams.append(name, scalarString(entry));\n } else if (value !== undefined && value !== null) {\n url.searchParams.append(name, scalarString(value));\n }\n}\n\nfunction appendSearchParam(params: URLSearchParams, name: string, value: unknown): void {\n if (Array.isArray(value)) {\n for (const entry of value) params.append(name, scalarString(entry));\n } else if (value !== undefined && value !== null) {\n params.append(name, scalarString(value));\n }\n}\n\nfunction scalarString(value: unknown): string {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n throw new IntegrationInvocationError(\n \"parameter_invalid\",\n \"Integration parameters must be strings, numbers, booleans, or arrays of them\",\n \"not_started\",\n false,\n );\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\nfunction resolveObject(\n document: Record<string, unknown>,\n value: unknown,\n label: string,\n): Record<string, unknown> {\n const resolved = resolveLocalRef(document, value);\n if (!isRecord(resolved)) {\n throw new IntegrationProtocolError(\"openapi_shape\", `OpenAPI ${label} is invalid`);\n }\n return resolved;\n}\n\nfunction resolveLocalRef(document: Record<string, unknown>, value: unknown): unknown {\n if (!isRecord(value) || typeof value.$ref !== \"string\") return value;\n if (!value.$ref.startsWith(\"#/\")) {\n throw new IntegrationProtocolError(\n \"openapi_external_ref\",\n \"External OpenAPI references are not supported; bundle the document first\",\n );\n }\n return value.$ref\n .slice(2)\n .split(\"/\")\n .map((part) => part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .reduce<unknown>((current, part) => (isRecord(current) ? current[part] : undefined), document);\n}\n\nfunction dereferenceSchema(\n document: Record<string, unknown>,\n value: unknown,\n seen = new Set<string>(),\n depth = 0,\n): JsonSchema {\n if (depth > 20) return {};\n if (isRecord(value) && typeof value.$ref === \"string\") {\n if (seen.has(value.$ref)) return {};\n const nextSeen = new Set(seen).add(value.$ref);\n return dereferenceSchema(document, resolveLocalRef(document, value), nextSeen, depth + 1);\n }\n if (!isRecord(value)) return {};\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"properties\" && isRecord(entry)) {\n result.properties = Object.fromEntries(\n Object.entries(entry).map(([name, schema]) => [\n name,\n dereferenceSchema(document, schema, seen, depth + 1),\n ]),\n );\n } else if (key === \"items\") {\n result.items = dereferenceSchema(document, entry, seen, depth + 1);\n } else if (key === \"allOf\" || key === \"anyOf\" || key === \"oneOf\") {\n result[key] = Array.isArray(entry)\n ? entry.map((schema) => dereferenceSchema(document, schema, seen, depth + 1))\n : [];\n } else if (key !== \"$ref\") {\n result[key] = entry;\n }\n }\n return result;\n}\n\nfunction normalizeMcpSchema(schema: JsonSchema): LocalMcpTool[\"inputSchema\"] {\n return {\n type: \"object\",\n properties: isRecord(schema.properties) ? schema.properties : {},\n required: Array.isArray(schema.required)\n ? schema.required.filter((entry): entry is string => typeof entry === \"string\")\n : [],\n additionalProperties: schema.additionalProperties === true,\n };\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { IntegrationProtocolError } from \"./types\";\n\nexport interface IntegrationDefinitionOAuth2Authentication {\n readonly kind: \"oauth2\";\n readonly provider: \"google\" | \"microsoft\";\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly scopes: readonly string[];\n readonly tokenPlacement: {\n readonly carrier: \"header\";\n readonly name: \"Authorization\";\n readonly prefix: \"Bearer \";\n };\n}\n\nexport type IntegrationDefinitionSource =\n | Readonly<{\n kind: \"google_discovery\";\n url: string;\n }>\n | Readonly<{\n kind: \"openapi\";\n url: string;\n operationPathPrefixes?: readonly string[];\n excludedOperationPathPrefixes?: readonly string[];\n /** Expose JSON bodies without expanding the provider entity graph. */\n schemaMode?: \"provider_validated_json\";\n }>;\n\nexport interface IntegrationDefinition {\n readonly id: string;\n readonly name: string;\n readonly summary: string;\n readonly protocol: \"openapi\";\n readonly provider: Readonly<{\n id: \"google\" | \"microsoft\";\n domain: string;\n }>;\n readonly source: IntegrationDefinitionSource;\n readonly baseUrl: string;\n readonly authentication: IntegrationDefinitionOAuth2Authentication;\n readonly healthCheck?: Readonly<{\n operationKey: string;\n arguments: Readonly<Record<string, unknown>>;\n }>;\n readonly facets: readonly IntegrationFacetDefinition[];\n}\n\nexport interface IntegrationFacetDefinition {\n readonly facetKey: string;\n readonly kind: \"knowledge_source\" | \"inbound_trigger\" | \"delivery_destination\" | \"identity_link\";\n readonly configSchema: Readonly<Record<string, unknown>>;\n readonly capabilities: Readonly<Record<string, unknown>>;\n}\n\nconst accountIdentityFacet = (provider: \"google\" | \"microsoft\"): IntegrationFacetDefinition => ({\n facetKey: \"account-identity\",\n kind: \"identity_link\",\n configSchema: { type: \"object\", properties: {}, additionalProperties: false },\n capabilities: {\n provider,\n connectionRequired: true,\n identity: \"connected_account\",\n },\n});\n\nconst driveKnowledgeFacet = (\n provider: \"google-drive\" | \"microsoft-onedrive\",\n): IntegrationFacetDefinition => ({\n facetKey: \"drive-content\",\n kind: \"knowledge_source\",\n configSchema: {\n type: \"object\",\n required: [\"sources\", \"destination\", \"syncCadence\", \"readPolicy\"],\n properties: {\n sources: {\n type: \"array\",\n minItems: 1,\n maxItems: 100,\n items: {\n type: \"object\",\n required: [\"id\", \"name\", \"mimeType\", \"sourceKind\", \"includeDescendants\"],\n properties: {\n id: { type: \"string\", minLength: 1, maxLength: 512 },\n name: { type: \"string\", minLength: 1, maxLength: 1024 },\n mimeType: { type: \"string\", minLength: 1, maxLength: 256 },\n driveId: { type: \"string\", minLength: 1, maxLength: 512 },\n sourceKind: {\n type: \"string\",\n enum:\n provider === \"google-drive\"\n ? [\"my_drive\", \"shared_drive\", \"folder\"]\n : [\"my_drive\", \"shared_library\", \"folder\"],\n },\n includeDescendants: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n destination: {\n type: \"object\",\n required: [\"authorityKind\", \"authorityAccountId\"],\n properties: {\n authorityKind: {\n type: \"string\",\n enum: [\"organization\", \"workspace\", \"personal\"],\n },\n authorityAccountId: { type: \"string\", minLength: 1, maxLength: 128 },\n authorityWorkspaceId: { type: \"string\", minLength: 1, maxLength: 128 },\n authoritySubjectId: { type: \"string\", minLength: 1, maxLength: 512 },\n collectionId: { type: \"string\", minLength: 1, maxLength: 512 },\n },\n additionalProperties: false,\n },\n syncCadence: { type: \"string\", enum: [\"manual\", \"hourly\", \"daily\"] },\n readPolicy: { type: \"string\", enum: [\"allow\", \"ask\", \"block\"] },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n sync: \"incremental\",\n cursor: provider === \"google-drive\" ? \"page_token\" : \"delta_link\",\n },\n});\n\nconst mailboxFacets = (\n provider: \"microsoft-outlook-mail\",\n): readonly IntegrationFacetDefinition[] => [\n {\n facetKey: \"mail-inbox\",\n kind: \"inbound_trigger\",\n configSchema: {\n type: \"object\",\n properties: {\n folder: { type: \"string\", minLength: 1, maxLength: 256 },\n unreadOnly: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n delivery: \"poll\",\n cursor: \"delta_link\",\n },\n },\n {\n facetKey: \"mail-delivery\",\n kind: \"delivery_destination\",\n configSchema: {\n type: \"object\",\n properties: {\n fromAlias: { type: \"string\", minLength: 1, maxLength: 512 },\n saveToSent: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider,\n connectionRequired: true,\n delivery: \"email\",\n },\n },\n accountIdentityFacet(\"microsoft\"),\n];\n\nconst googleDiscoveryUrl = (service: string, version: string): string =>\n `https://www.googleapis.com/discovery/v1/apis/${service}/${version}/rest`;\n\nconst googleOAuth = (scopes: readonly string[]): IntegrationDefinitionOAuth2Authentication => ({\n kind: \"oauth2\",\n provider: \"google\",\n authorizationUrl: \"https://accounts.google.com/o/oauth2/v2/auth\",\n tokenUrl: \"https://oauth2.googleapis.com/token\",\n scopes: [\"openid\", \"email\", \"profile\", ...scopes],\n tokenPlacement: { carrier: \"header\", name: \"Authorization\", prefix: \"Bearer \" },\n});\n\nexport const GOOGLE_DRIVE_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"google-drive\",\n name: \"Google Drive\",\n summary: \"Files, folders, permissions, and shared drives.\",\n protocol: \"openapi\",\n provider: { id: \"google\", domain: \"www.googleapis.com\" },\n source: { kind: \"google_discovery\", url: googleDiscoveryUrl(\"drive\", \"v3\") },\n baseUrl: \"https://www.googleapis.com/drive/v3/\",\n authentication: googleOAuth([\"https://www.googleapis.com/auth/drive\"]),\n healthCheck: {\n operationKey: \"drive.about.get\",\n arguments: { query: { fields: \"user\" } },\n },\n facets: [driveKnowledgeFacet(\"google-drive\"), accountIdentityFacet(\"google\")],\n};\n\nexport const MICROSOFT_GRAPH_OPENAPI_URL =\n \"https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/openapi/v1.0/openapi.yaml\";\nexport const MICROSOFT_GRAPH_BASE_URL = \"https://graph.microsoft.com/v1.0\";\n\nconst microsoftOAuth = (scopes: readonly string[]): IntegrationDefinitionOAuth2Authentication => ({\n kind: \"oauth2\",\n provider: \"microsoft\",\n authorizationUrl: \"https://login.microsoftonline.com/common/oauth2/v2.0/authorize\",\n tokenUrl: \"https://login.microsoftonline.com/common/oauth2/v2.0/token\",\n scopes: [\"offline_access\", \"User.Read\", ...scopes],\n tokenPlacement: { carrier: \"header\", name: \"Authorization\", prefix: \"Bearer \" },\n});\n\nexport const MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-mail\",\n name: \"Outlook Mail\",\n summary: \"Messages, folders, attachments, settings, and sending mail.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n schemaMode: \"provider_validated_json\",\n operationPathPrefixes: [\n \"/me/messages\",\n \"/me/mailFolders\",\n \"/me/sendMail\",\n \"/me/getMailTips\",\n \"/me/inferenceClassification\",\n \"/me/mailboxSettings\",\n \"/me/outlook\",\n ],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Mail.ReadWrite\", \"Mail.Send\", \"MailboxSettings.ReadWrite\"]),\n facets: mailboxFacets(\"microsoft-outlook-mail\"),\n};\n\nexport const MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-calendar\",\n name: \"Outlook Calendar\",\n summary: \"Calendars, events, availability, and scheduling.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n schemaMode: \"provider_validated_json\",\n operationPathPrefixes: [\n \"/me/calendar\",\n \"/me/calendars\",\n \"/me/calendarGroups\",\n \"/me/calendarView\",\n \"/me/events\",\n \"/me/findMeetingTimes\",\n \"/me/reminderView\",\n ],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Calendars.ReadWrite\"]),\n facets: [\n {\n facetKey: \"calendar-events\",\n kind: \"inbound_trigger\",\n configSchema: {\n type: \"object\",\n properties: {\n calendarId: { type: \"string\", minLength: 1, maxLength: 512 },\n lookaheadDays: { type: \"integer\", minimum: 1, maximum: 365 },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider: \"microsoft-outlook-calendar\",\n connectionRequired: true,\n delivery: \"poll\",\n cursor: \"delta_link\",\n },\n },\n {\n facetKey: \"calendar-delivery\",\n kind: \"delivery_destination\",\n configSchema: {\n type: \"object\",\n properties: {\n calendarId: { type: \"string\", minLength: 1, maxLength: 512 },\n },\n additionalProperties: false,\n },\n capabilities: {\n provider: \"microsoft-outlook-calendar\",\n connectionRequired: true,\n delivery: \"calendar_event\",\n },\n },\n accountIdentityFacet(\"microsoft\"),\n ],\n};\n\nexport const MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-outlook-contacts\",\n name: \"Outlook Contacts\",\n summary: \"Contacts, contact folders, and people suggestions.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n schemaMode: \"provider_validated_json\",\n operationPathPrefixes: [\"/me/contacts\", \"/me/contactFolders\", \"/me/people\"],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Contacts.ReadWrite\", \"People.Read\"]),\n facets: [accountIdentityFacet(\"microsoft\")],\n};\n\nexport const MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION: IntegrationDefinition = {\n id: \"microsoft-onedrive\",\n name: \"OneDrive\",\n summary: \"Drives, files, folders, sharing links, and permissions.\",\n protocol: \"openapi\",\n provider: { id: \"microsoft\", domain: \"graph.microsoft.com\" },\n source: {\n kind: \"openapi\",\n url: MICROSOFT_GRAPH_OPENAPI_URL,\n schemaMode: \"provider_validated_json\",\n operationPathPrefixes: [\"/me/drive\", \"/me/drives\", \"/drives\", \"/shares\"],\n // Excel's nested workbook API is a separate surface, not file management.\n excludedOperationPathPrefixes: [\"/drives/{drive-id}/items/{driveItem-id}/workbook\"],\n },\n baseUrl: MICROSOFT_GRAPH_BASE_URL,\n authentication: microsoftOAuth([\"Files.ReadWrite.All\"]),\n facets: [driveKnowledgeFacet(\"microsoft-onedrive\"), accountIdentityFacet(\"microsoft\")],\n};\n\nexport const CORE_INTEGRATION_DEFINITIONS: readonly IntegrationDefinition[] = [\n GOOGLE_DRIVE_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION,\n MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION,\n MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION,\n];\n\nexport function integrationDefinitionById(id: string): IntegrationDefinition | undefined {\n return CORE_INTEGRATION_DEFINITIONS.find((definition) => definition.id === id);\n}\n\nexport function integrationDefinitionProviderDomain(definition: IntegrationDefinition): string {\n return definition.provider.domain;\n}\n\nexport function integrationFacetDefinitions(\n definitionId: string | null | undefined,\n): readonly IntegrationFacetDefinition[] {\n return definitionId ? (integrationDefinitionById(definitionId)?.facets ?? []) : [];\n}\n\nexport function filterOpenApiDocumentForDefinition(\n document: Record<string, unknown>,\n definition: IntegrationDefinition,\n): Record<string, unknown> {\n if (definition.source.kind !== \"openapi\" || !definition.source.operationPathPrefixes?.length) {\n return document;\n }\n const operationPathPrefixes = definition.source.operationPathPrefixes;\n const excludedOperationPathPrefixes = definition.source.excludedOperationPathPrefixes ?? [];\n if (!isRecord(document.paths)) {\n throw new IntegrationProtocolError(\"openapi_paths\", \"OpenAPI document has no paths object\");\n }\n const paths = Object.fromEntries(\n Object.entries(document.paths).filter(\n ([path]) =>\n operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)) &&\n !excludedOperationPathPrefixes.some(\n (prefix) => path === prefix || path.startsWith(`${prefix}/`),\n ),\n ),\n );\n if (Object.keys(paths).length === 0) {\n throw new IntegrationProtocolError(\n \"integration_definition_empty\",\n `${definition.name} did not match any operations in the supplied OpenAPI document`,\n );\n }\n return {\n ...document,\n paths,\n servers: [{ url: definition.baseUrl }],\n };\n}\n\nexport function googleDiscoveryToOpenApi(discovery: unknown): Record<string, unknown> {\n if (!isRecord(discovery)) {\n throw new IntegrationProtocolError(\n \"google_discovery_shape\",\n \"Google Discovery document is invalid\",\n );\n }\n const rootUrl = stringValue(discovery.rootUrl) ?? stringValue(discovery.baseUrl);\n const servicePath = stringValue(discovery.servicePath) ?? \"\";\n if (!rootUrl || !URL.canParse(rootUrl)) {\n throw new IntegrationProtocolError(\n \"google_discovery_server\",\n \"Google Discovery document has no valid root URL\",\n );\n }\n const paths: Record<string, unknown> = {};\n collectGoogleMethods(discovery, discovery.methods, paths);\n collectGoogleResources(discovery, discovery.resources, paths);\n if (Object.keys(paths).length === 0) {\n throw new IntegrationProtocolError(\n \"google_discovery_empty\",\n \"Google Discovery document exposes no methods\",\n );\n }\n const scopes =\n isRecord(discovery.auth) && isRecord(discovery.auth.oauth2)\n ? discovery.auth.oauth2.scopes\n : undefined;\n const scopeMap = isRecord(scopes)\n ? Object.fromEntries(\n Object.entries(scopes).map(([scope, value]) => [\n scope,\n isRecord(value) && typeof value.description === \"string\" ? value.description : \"\",\n ]),\n )\n : {};\n return {\n openapi: \"3.1.0\",\n info: {\n title: stringValue(discovery.title) ?? stringValue(discovery.name) ?? \"Google API\",\n description: stringValue(discovery.description) ?? \"Google Discovery API\",\n version: stringValue(discovery.version) ?? \"v1\",\n },\n servers: [{ url: new URL(servicePath, rootUrl).toString() }],\n paths,\n components: {\n schemas: Object.fromEntries(\n Object.entries(isRecord(discovery.schemas) ? discovery.schemas : {}).map(\n ([name, schema]) => [name, convertGoogleSchema(schema)],\n ),\n ),\n securitySchemes: {\n googleOAuth2: {\n type: \"oauth2\",\n flows: {\n authorizationCode: {\n authorizationUrl: \"https://accounts.google.com/o/oauth2/v2/auth\",\n tokenUrl: \"https://oauth2.googleapis.com/token\",\n scopes: scopeMap,\n },\n },\n },\n },\n },\n security: Object.keys(scopeMap).length > 0 ? [{ googleOAuth2: [] }] : [],\n };\n}\n\nfunction collectGoogleResources(\n document: Record<string, unknown>,\n value: unknown,\n paths: Record<string, unknown>,\n): void {\n if (!isRecord(value)) return;\n for (const resource of Object.values(value)) {\n if (!isRecord(resource)) continue;\n collectGoogleMethods(document, resource.methods, paths);\n collectGoogleResources(document, resource.resources, paths);\n }\n}\n\nfunction collectGoogleMethods(\n document: Record<string, unknown>,\n value: unknown,\n paths: Record<string, unknown>,\n): void {\n if (!isRecord(value)) return;\n for (const [fallbackId, rawMethod] of Object.entries(value)) {\n if (!isRecord(rawMethod)) continue;\n const path = stringValue(rawMethod.path);\n const httpMethod = stringValue(rawMethod.httpMethod)?.toLowerCase();\n if (!path || !httpMethod) continue;\n const parameters = Object.entries(isRecord(rawMethod.parameters) ? rawMethod.parameters : {})\n .sort(([left], [right]) => left.localeCompare(right))\n .flatMap(([name, rawParameter]): Record<string, unknown>[] => {\n if (!isRecord(rawParameter)) return [];\n const location = rawParameter.location === \"path\" ? \"path\" : \"query\";\n return [\n {\n name,\n in: location,\n required: location === \"path\" || rawParameter.required === true,\n ...(stringValue(rawParameter.description)\n ? { description: stringValue(rawParameter.description) }\n : {}),\n schema: convertGoogleSchema(rawParameter),\n },\n ];\n });\n const requestRef = isRecord(rawMethod.request)\n ? stringValue(rawMethod.request.$ref)\n : undefined;\n const responseRef = isRecord(rawMethod.response)\n ? stringValue(rawMethod.response.$ref)\n : undefined;\n const operation: Record<string, unknown> = {\n operationId: stringValue(rawMethod.id) ?? fallbackId,\n // Discovery descriptions are often full documentation paragraphs. Keep\n // them as descriptions and use the stable method identity for the short\n // OpenGeni tool display name.\n summary: stringValue(rawMethod.id) ?? fallbackId,\n description: stringValue(rawMethod.description),\n parameters,\n responses: {\n \"200\": {\n description: \"Successful response\",\n ...(responseRef\n ? {\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${escapeJsonPointer(responseRef)}` },\n },\n },\n }\n : {}),\n },\n },\n ...(Array.isArray(rawMethod.scopes) && rawMethod.scopes.length > 0\n ? { security: [{ googleOAuth2: rawMethod.scopes }] }\n : {}),\n };\n if (requestRef) {\n operation.requestBody = {\n required: true,\n content: {\n \"application/json\": {\n schema: { $ref: `#/components/schemas/${escapeJsonPointer(requestRef)}` },\n },\n },\n };\n }\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n const existing = isRecord(paths[normalizedPath]) ? paths[normalizedPath] : {};\n paths[normalizedPath] = { ...existing, [httpMethod]: operation };\n }\n}\n\nfunction convertGoogleSchema(value: unknown, depth = 0): Record<string, unknown> {\n if (!isRecord(value) || depth > 20) return {};\n if (typeof value.$ref === \"string\") {\n return { $ref: `#/components/schemas/${escapeJsonPointer(value.$ref)}` };\n }\n const result: Record<string, unknown> = {};\n const type = stringValue(value.type);\n if (type) result.type = type === \"any\" ? undefined : type;\n for (const key of [\n \"description\",\n \"format\",\n \"pattern\",\n \"minimum\",\n \"maximum\",\n \"default\",\n ] as const) {\n if (value[key] !== undefined) result[key] = value[key];\n }\n if (Array.isArray(value.enum)) result.enum = value.enum;\n if (isRecord(value.properties)) {\n result.type = result.type ?? \"object\";\n result.properties = Object.fromEntries(\n Object.entries(value.properties).map(([name, schema]) => [\n name,\n convertGoogleSchema(schema, depth + 1),\n ]),\n );\n }\n if (value.items !== undefined) {\n result.type = result.type ?? \"array\";\n result.items = convertGoogleSchema(value.items, depth + 1);\n }\n if (value.additionalProperties !== undefined) {\n result.additionalProperties =\n value.additionalProperties === true\n ? true\n : convertGoogleSchema(value.additionalProperties, depth + 1);\n }\n if (Array.isArray(value.required)) result.required = value.required;\n return Object.fromEntries(Object.entries(result).filter(([, entry]) => entry !== undefined));\n}\n\nfunction escapeJsonPointer(value: string): string {\n return value.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n","/**\n * Reviewed consent copy for the core API integration definitions.\n *\n * Presentation only: nothing here grants a scope, selects a connection, or\n * replaces server-side authorization. The copy used to live hardcoded in the\n * web bundle (`REVIEWED_INTEGRATION_EXPERIENCES`); it is served with the\n * definition now so polishing a consent screen is a data change, not a\n * frontend release. The web keeps its generic fallback for any definition or\n * field missing here. Gmail's reviewed presentation lives on its catalog row\n * instead (`data/catalog/curated.json`): Gmail is a Connector, not one of\n * these API integration definitions.\n *\n * MCP connectors carry the same shape on their curated catalog row\n * (`presentation` in `data/catalog/curated.json` -> importer ->\n * `capability_catalog_items.metadata.presentation`).\n */\n\nexport type IntegrationPresentationIcon = \"calendar\" | \"cloud\" | \"contacts\" | \"files\" | \"mail\";\n\nexport type IntegrationPresentationCopy = {\n readonly providerName?: string;\n readonly icon?: IntegrationPresentationIcon;\n readonly introduction?: string;\n readonly capabilities?: readonly { readonly title: string; readonly description: string }[];\n readonly permissionSummary?: string;\n readonly scopeLabels?: Readonly<\n Record<string, { readonly label: string; readonly description: string }>\n >;\n};\n\nexport const INTEGRATION_DEFINITION_PRESENTATIONS: Readonly<\n Record<string, IntegrationPresentationCopy>\n> = {\n \"google-drive\": {\n providerName: \"Google\",\n icon: \"files\",\n introduction: \"Let agents work with files in the Google Drive account you choose.\",\n capabilities: [\n {\n title: \"Find files and folders\",\n description: \"Browse and search content in My Drive and shared drives.\",\n },\n {\n title: \"Create and update content\",\n description: \"Work with files and folders through the reviewed Drive tools.\",\n },\n {\n title: \"Manage sharing\",\n description: \"Review and update links, permissions, and shared-drive content.\",\n },\n ],\n permissionSummary:\n \"Google asks for access to the Drive account you approve, including files shared with that account.\",\n scopeLabels: {\n \"https://www.googleapis.com/auth/drive\": {\n label: \"Work with Google Drive files\",\n description: \"See, create, edit, organize, and share files available to this account.\",\n },\n },\n },\n \"microsoft-outlook-mail\": {\n providerName: \"Microsoft\",\n icon: \"mail\",\n introduction: \"Let agents work with mail in the Microsoft account you choose.\",\n capabilities: [\n {\n title: \"Find and understand mail\",\n description: \"Search messages, folders, and attachments for useful context.\",\n },\n {\n title: \"Draft and send messages\",\n description: \"Prepare, update, and send mail through the reviewed Outlook tools.\",\n },\n {\n title: \"Manage mailbox settings\",\n description: \"Work with supported folders, classifications, and mailbox preferences.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for mail and mailbox-setting access for the account you approve.\",\n scopeLabels: {\n \"Mail.ReadWrite\": {\n label: \"Read and update mail\",\n description: \"Work with messages, folders, and attachments in this mailbox.\",\n },\n \"Mail.Send\": {\n label: \"Send mail\",\n description: \"Send messages as the connected Microsoft account.\",\n },\n \"MailboxSettings.ReadWrite\": {\n label: \"Manage mailbox settings\",\n description: \"Read and update supported Outlook mailbox preferences.\",\n },\n },\n },\n \"microsoft-outlook-calendar\": {\n providerName: \"Microsoft\",\n icon: \"calendar\",\n introduction: \"Let agents help coordinate the calendars in your Microsoft account.\",\n capabilities: [\n {\n title: \"Understand your schedule\",\n description: \"Review calendars, events, availability, and reminders.\",\n },\n {\n title: \"Plan meetings\",\n description: \"Find suitable times and coordinate calendar activity.\",\n },\n {\n title: \"Manage events\",\n description: \"Create and update events through the reviewed calendar tools.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for permission to view and manage calendars for the account you approve.\",\n scopeLabels: {\n \"Calendars.ReadWrite\": {\n label: \"View and manage calendars\",\n description: \"Read, create, update, and organize calendar events.\",\n },\n },\n },\n \"microsoft-outlook-contacts\": {\n providerName: \"Microsoft\",\n icon: \"contacts\",\n introduction: \"Let agents work with contacts in your Microsoft account.\",\n capabilities: [\n {\n title: \"Find people\",\n description: \"Look up contacts and relevant people suggestions.\",\n },\n {\n title: \"Organize contacts\",\n description: \"Work with contacts and contact folders.\",\n },\n {\n title: \"Keep details current\",\n description: \"Create or update contact information through reviewed tools.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for contact access and people suggestions for the account you approve.\",\n scopeLabels: {\n \"Contacts.ReadWrite\": {\n label: \"View and manage contacts\",\n description: \"Read, create, update, and organize contacts and contact folders.\",\n },\n \"People.Read.All\": {\n label: \"Find relevant people\",\n description: \"Use people suggestions available to the connected account.\",\n },\n },\n },\n \"microsoft-onedrive\": {\n providerName: \"Microsoft\",\n icon: \"cloud\",\n introduction: \"Let agents work with files in the Microsoft account you choose.\",\n capabilities: [\n {\n title: \"Find files and folders\",\n description: \"Browse drives, folders, shared items, and sites available to the account.\",\n },\n {\n title: \"Create and update content\",\n description: \"Work with OneDrive and SharePoint files through reviewed tools.\",\n },\n {\n title: \"Manage sharing\",\n description: \"Review and update sharing links and permissions.\",\n },\n ],\n permissionSummary:\n \"Microsoft asks for file and site access anywhere the connected account already has access.\",\n scopeLabels: {\n \"Files.ReadWrite.All\": {\n label: \"Work with accessible files\",\n description: \"Read, create, update, and organize files available to this account.\",\n },\n \"Sites.ReadWrite.All\": {\n label: \"Work with accessible sites\",\n description: \"Read and update files in SharePoint sites available to this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MACA;AAAA,QACE,OAAO;AAAA,QACP,aAAa;AAAA,MACf;AAAA,IACF;AAAA,IACA,mBACE;AAAA,IACF,aAAa;AAAA,MACX,uBAAuB;AAAA,QACrB,OAAO;AAAA,QACP,aAAa;AAAA,MACf;AAAA,MACA,uBAAuB;AAAA,QACrB,OAAO;AAAA,QACP,aAAa;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;","names":["adapter","isRecord","normalizeMcpSchema","isRecord","stringValue"]}
@@ -17,6 +17,9 @@ export type IntegrationDefinitionSource = Readonly<{
17
17
  kind: "openapi";
18
18
  url: string;
19
19
  operationPathPrefixes?: readonly string[];
20
+ excludedOperationPathPrefixes?: readonly string[];
21
+ /** Expose JSON bodies without expanding the provider entity graph. */
22
+ schemaMode?: "provider_validated_json";
20
23
  }>;
21
24
  export interface IntegrationDefinition {
22
25
  readonly id: string;
package/dist/openapi.d.ts CHANGED
@@ -26,6 +26,7 @@ export interface CompileOpenApiOptions {
26
26
  readonly sourceUrl?: string;
27
27
  readonly baseUrl?: string;
28
28
  readonly provider?: string;
29
+ readonly schemaMode?: "provider_validated_json";
29
30
  }
30
31
  export interface OpenApiServerOptions {
31
32
  readonly revision: OpenApiRevision;
@@ -49,7 +50,9 @@ export type OpenApiAuthDiscovery = {
49
50
  scheme: string;
50
51
  };
51
52
  type LocalMcpTool = Awaited<ReturnType<MCPServer["listTools"]>>[number];
52
- export declare function parseOpenApiDocument(source: string | Uint8Array): Record<string, unknown>;
53
+ export declare function parseOpenApiDocument(source: string | Uint8Array, options?: {
54
+ maxBytes?: number;
55
+ }): Record<string, unknown>;
53
56
  export declare function compileOpenApiRevision(source: string | Uint8Array | Record<string, unknown>, options: CompileOpenApiOptions): OpenApiRevision;
54
57
  export declare function discoverOpenApiAuth(document: Record<string, unknown>): OpenApiAuthDiscovery;
55
58
  export declare class OpenApiMcpServer implements MCPServer {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/capabilities",
3
- "version": "0.3.3-canary.14",
3
+ "version": "0.3.3-canary.16",
4
4
  "description": "Protocol-neutral capability integration compilers and local MCP adapters for OpenGeni.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@openai/agents": "0.14.3",
39
- "@opengeni/network": "^0.3.1-canary.14",
39
+ "@opengeni/network": "^0.3.1-canary.16",
40
40
  "graphql": "^16.12.0",
41
41
  "js-yaml": "4.1.1"
42
42
  },
package/src/http.ts CHANGED
@@ -6,6 +6,7 @@ import { IntegrationInvocationError } from "./types";
6
6
  export const DEFAULT_INTEGRATION_TIMEOUT_MS = 30_000;
7
7
  export const DEFAULT_INTEGRATION_RESPONSE_BYTES = 4 * 1024 * 1024;
8
8
  export const MAX_INTEGRATION_SPEC_BYTES = 8 * 1024 * 1024;
9
+ export const MAX_CURATED_INTEGRATION_SPEC_BYTES = 64 * 1024 * 1024;
9
10
  export const MAX_INTEGRATION_TOOLS = 2_000;
10
11
 
11
12
  export async function fetchIntegrationSourceDocument(
@@ -22,6 +22,9 @@ export type IntegrationDefinitionSource =
22
22
  kind: "openapi";
23
23
  url: string;
24
24
  operationPathPrefixes?: readonly string[];
25
+ excludedOperationPathPrefixes?: readonly string[];
26
+ /** Expose JSON bodies without expanding the provider entity graph. */
27
+ schemaMode?: "provider_validated_json";
25
28
  }>;
26
29
 
27
30
  export interface IntegrationDefinition {
@@ -213,6 +216,7 @@ export const MICROSOFT_OUTLOOK_MAIL_INTEGRATION_DEFINITION: IntegrationDefinitio
213
216
  source: {
214
217
  kind: "openapi",
215
218
  url: MICROSOFT_GRAPH_OPENAPI_URL,
219
+ schemaMode: "provider_validated_json",
216
220
  operationPathPrefixes: [
217
221
  "/me/messages",
218
222
  "/me/mailFolders",
@@ -237,6 +241,7 @@ export const MICROSOFT_OUTLOOK_CALENDAR_INTEGRATION_DEFINITION: IntegrationDefin
237
241
  source: {
238
242
  kind: "openapi",
239
243
  url: MICROSOFT_GRAPH_OPENAPI_URL,
244
+ schemaMode: "provider_validated_json",
240
245
  operationPathPrefixes: [
241
246
  "/me/calendar",
242
247
  "/me/calendars",
@@ -297,10 +302,11 @@ export const MICROSOFT_OUTLOOK_CONTACTS_INTEGRATION_DEFINITION: IntegrationDefin
297
302
  source: {
298
303
  kind: "openapi",
299
304
  url: MICROSOFT_GRAPH_OPENAPI_URL,
305
+ schemaMode: "provider_validated_json",
300
306
  operationPathPrefixes: ["/me/contacts", "/me/contactFolders", "/me/people"],
301
307
  },
302
308
  baseUrl: MICROSOFT_GRAPH_BASE_URL,
303
- authentication: microsoftOAuth(["Contacts.ReadWrite", "People.Read.All"]),
309
+ authentication: microsoftOAuth(["Contacts.ReadWrite", "People.Read"]),
304
310
  facets: [accountIdentityFacet("microsoft")],
305
311
  };
306
312
 
@@ -313,10 +319,13 @@ export const MICROSOFT_ONEDRIVE_INTEGRATION_DEFINITION: IntegrationDefinition =
313
319
  source: {
314
320
  kind: "openapi",
315
321
  url: MICROSOFT_GRAPH_OPENAPI_URL,
316
- operationPathPrefixes: ["/me/drive", "/me/drives", "/me/followedSites", "/drives", "/shares"],
322
+ schemaMode: "provider_validated_json",
323
+ operationPathPrefixes: ["/me/drive", "/me/drives", "/drives", "/shares"],
324
+ // Excel's nested workbook API is a separate surface, not file management.
325
+ excludedOperationPathPrefixes: ["/drives/{drive-id}/items/{driveItem-id}/workbook"],
317
326
  },
318
327
  baseUrl: MICROSOFT_GRAPH_BASE_URL,
319
- authentication: microsoftOAuth(["Files.ReadWrite.All", "Sites.ReadWrite.All"]),
328
+ authentication: microsoftOAuth(["Files.ReadWrite.All"]),
320
329
  facets: [driveKnowledgeFacet("microsoft-onedrive"), accountIdentityFacet("microsoft")],
321
330
  };
322
331
 
@@ -350,12 +359,17 @@ export function filterOpenApiDocumentForDefinition(
350
359
  return document;
351
360
  }
352
361
  const operationPathPrefixes = definition.source.operationPathPrefixes;
362
+ const excludedOperationPathPrefixes = definition.source.excludedOperationPathPrefixes ?? [];
353
363
  if (!isRecord(document.paths)) {
354
364
  throw new IntegrationProtocolError("openapi_paths", "OpenAPI document has no paths object");
355
365
  }
356
366
  const paths = Object.fromEntries(
357
- Object.entries(document.paths).filter(([path]) =>
358
- operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)),
367
+ Object.entries(document.paths).filter(
368
+ ([path]) =>
369
+ operationPathPrefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)) &&
370
+ !excludedOperationPathPrefixes.some(
371
+ (prefix) => path === prefix || path.startsWith(`${prefix}/`),
372
+ ),
359
373
  ),
360
374
  );
361
375
  if (Object.keys(paths).length === 0) {
package/src/openapi.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  DEFAULT_INTEGRATION_RESPONSE_BYTES,
7
7
  DEFAULT_INTEGRATION_TIMEOUT_MS,
8
8
  MAX_INTEGRATION_SPEC_BYTES,
9
+ MAX_CURATED_INTEGRATION_SPEC_BYTES,
9
10
  MAX_INTEGRATION_TOOLS,
10
11
  fetchWithDeadline,
11
12
  readIntegrationResponse,
@@ -59,6 +60,7 @@ export interface CompileOpenApiOptions {
59
60
  readonly sourceUrl?: string;
60
61
  readonly baseUrl?: string;
61
62
  readonly provider?: string;
63
+ readonly schemaMode?: "provider_validated_json";
62
64
  }
63
65
 
64
66
  export interface OpenApiServerOptions {
@@ -102,12 +104,25 @@ const forbiddenParameterHeaders = new Set([
102
104
  "transfer-encoding",
103
105
  ]);
104
106
 
105
- export function parseOpenApiDocument(source: string | Uint8Array): Record<string, unknown> {
107
+ export function parseOpenApiDocument(
108
+ source: string | Uint8Array,
109
+ options: { maxBytes?: number } = {},
110
+ ): Record<string, unknown> {
111
+ const maxBytes = options.maxBytes ?? MAX_INTEGRATION_SPEC_BYTES;
112
+ if (
113
+ !Number.isSafeInteger(maxBytes) ||
114
+ maxBytes < 1 ||
115
+ maxBytes > MAX_CURATED_INTEGRATION_SPEC_BYTES
116
+ ) {
117
+ throw new RangeError(
118
+ `OpenAPI parser limit must be between 1 and ${MAX_CURATED_INTEGRATION_SPEC_BYTES} bytes`,
119
+ );
120
+ }
106
121
  const bytes = typeof source === "string" ? Buffer.byteLength(source) : source.byteLength;
107
- if (bytes === 0 || bytes > MAX_INTEGRATION_SPEC_BYTES) {
122
+ if (bytes === 0 || bytes > maxBytes) {
108
123
  throw new IntegrationProtocolError(
109
124
  "openapi_spec_size",
110
- `OpenAPI document must be between 1 and ${MAX_INTEGRATION_SPEC_BYTES} bytes`,
125
+ `OpenAPI document must be between 1 and ${maxBytes} bytes`,
111
126
  );
112
127
  }
113
128
  const text =
@@ -142,7 +157,9 @@ export function compileOpenApiRevision(
142
157
  options: CompileOpenApiOptions,
143
158
  ): OpenApiRevision {
144
159
  const document = isRecord(source) ? source : parseOpenApiDocument(source);
145
- const contentSha256 = sha256Hex(canonicalJson(document));
160
+ const contentSha256 = sha256Hex(
161
+ canonicalJson(options.schemaMode ? { document, schemaMode: options.schemaMode } : document),
162
+ );
146
163
  const revisionId = immutableRevisionId("openapi", contentSha256);
147
164
  const info = isRecord(document.info) ? document.info : {};
148
165
  const documentServers = readServers(document.servers, options.baseUrl, options.sourceUrl);
@@ -167,7 +184,7 @@ export function compileOpenApiRevision(
167
184
  sharedParameters,
168
185
  readParameters(document, operation.parameters),
169
186
  );
170
- const requestBody = readRequestBody(document, operation.requestBody);
187
+ const requestBody = readRequestBody(document, operation.requestBody, options.schemaMode);
171
188
  const serverUrl = firstServerUrl(
172
189
  readServers(operation.servers, undefined, undefined),
173
190
  pathServers,
@@ -177,7 +194,9 @@ export function compileOpenApiRevision(
177
194
  operation.security === undefined ? documentSecurity : readSecurity(operation.security);
178
195
  const safety = classifyHttpSafety(method, operation);
179
196
  const inputSchema = operationInputSchema(parameters, requestBody);
180
- const outputSchema = operationOutputSchema(document, operation.responses);
197
+ const outputSchema = options.schemaMode
198
+ ? undefined
199
+ : operationOutputSchema(document, operation.responses);
181
200
  const summary = stringValue(operation.summary) ?? stringValue(operation.description);
182
201
  tools.push({
183
202
  id,
@@ -554,6 +573,7 @@ function mergeParameters(
554
573
  function readRequestBody(
555
574
  document: Record<string, unknown>,
556
575
  value: unknown,
576
+ schemaMode?: CompileOpenApiOptions["schemaMode"],
557
577
  ): OpenApiOperationBinding["requestBody"] | undefined {
558
578
  if (value === undefined) return undefined;
559
579
  const body = resolveObject(document, value, "request body");
@@ -561,7 +581,15 @@ function readRequestBody(
561
581
  const schemas: Record<string, JsonSchema> = {};
562
582
  for (const [contentType, rawMedia] of Object.entries(body.content)) {
563
583
  if (!isRecord(rawMedia)) continue;
564
- schemas[contentType.toLowerCase()] = dereferenceSchema(document, rawMedia.schema);
584
+ const normalizedType = contentType.toLowerCase();
585
+ const jsonBody = normalizedType === "application/json" || normalizedType.endsWith("+json");
586
+ schemas[normalizedType] =
587
+ schemaMode === "provider_validated_json" && jsonBody
588
+ ? {
589
+ description:
590
+ "Request JSON for this API operation. The provider validates fields; follow the operation documentation.",
591
+ }
592
+ : dereferenceSchema(document, rawMedia.schema);
565
593
  }
566
594
  const contentTypes = Object.keys(schemas);
567
595
  return contentTypes.length === 0