@apollo/client-ai-apps 0.6.1 → 0.6.3

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/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ ## 0.6.3 (2026-03-13)
2
+
3
+ ### Fixes
4
+
5
+ #### Fix ChatGPT page reload getting stuck
6
+
7
+ Fixes an issue where reloading the page in ChatGPT would cause the app to get stuck indefinitely. After a reload, ChatGPT does not re-send the `ui/notifications/tool-result` notification, so the app is stuck waiting for an event that would never arrive.
8
+
9
+ #### Fix issue with operation description on executed queries
10
+
11
+ Fixes an issue where a query executed by the client through the Apollo MCP Server `execute` tool maintained operation descriptions on the query.
12
+
13
+ ## 0.6.2 (2026-03-12)
14
+
15
+ ### Fixes
16
+
17
+ #### Strip operation description from manifest `body` field
18
+
19
+ When a GraphQL operation uses an operation description as the tool description, the description is removed from the operation `body` in the manifest. This fixes a compatibility issue with Apollo MCP Server which currently does not support operation descriptions.
20
+
1
21
  ## 0.6.1 (2026-03-11)
2
22
 
3
23
  ### Features
@@ -1 +1 @@
1
- {"version":3,"file":"ApolloClient.d.ts","sourceRoot":"","sources":["../../../src/mcp/core/ApolloClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,YAAY,IAAI,gBAAgB,EAEjC,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EACnB,MAAM,gBAAgB,CAAC;AAKxB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAE/E,OAAO,EACL,cAAc,EAMf,MAAM,0BAA0B,CAAC;AAGlC,MAAM,CAAC,OAAO,WAAW,YAAY,CAAC;IACpC,UAAiB,OAAQ,SAAQ,IAAI,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC;QACrE,IAAI,CAAC,EAAE,gBAAgB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACxC,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AQ,CAAC,CAAC,cAAc,CAAC,QAAQ;gBAIrB,OAAO,EAAE,YAAY,CAAC,OAAO;IA6BzC,IAAI;IAKJ,IAAI,SAAS,wCAEZ;IAED,cAAc;IAId,UAAU,CACR,CAAC,GAAG,GAAG,EACP,UAAU,SAAS,kBAAkB,GAAG,kBAAkB,EAC1D,OAAO,EAAE,iBAAiB,CAAC,UAAU,EAAE,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,UAAU,CAAC;IAyC5E,OAAO;;MAsBJ;CACJ"}
@@ -1,6 +1,6 @@
1
1
  import { ApolloLink, ApolloClient as BaseApolloClient, DocumentTransform, } from "@apollo/client";
2
2
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
3
- import { parse } from "graphql";
3
+ import { parse, visit } from "graphql";
4
4
  import { equal } from "@wry/equality";
5
5
  import { __DEV__ } from "@apollo/client/utilities/environment";
6
6
  import { ToolCallLink } from "../link/ToolCallLink.js";
@@ -22,7 +22,12 @@ export class ApolloClient extends BaseApolloClient {
22
22
  link,
23
23
  // Strip out the prefetch/tool directives so they don't get sent with the operation to the server
24
24
  documentTransform: new DocumentTransform((document) => {
25
- return removeDirectivesFromDocument([{ name: "prefetch" }, { name: "tool" }], document);
25
+ const serverDocument = removeDirectivesFromDocument([{ name: "prefetch" }, { name: "tool" }], document);
26
+ return visit(serverDocument, {
27
+ OperationDefinition(node) {
28
+ return { ...node, description: undefined };
29
+ },
30
+ });
26
31
  }).concat(options.documentTransform ?? DocumentTransform.identity()),
27
32
  });
28
33
  this.manifest = options.manifest;
@@ -1 +1 @@
1
- {"version":3,"file":"ApolloClient.js","sourceRoot":"","sources":["../../../src/mcp/core/ApolloClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,YAAY,IAAI,gBAAgB,EAChC,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,KAA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IAAgB;IAC/C,IAAI,eAAe,GAAG,IAAI,CAAC;IAE3B,OAAO,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,eAAe,GAAG,eAAe,CAAC,KAAK,CAAC;IAC1C,CAAC;IAED,IACE,CAAC,WAAW,CAAC,eAAe,CAAC;QAC7B,eAAe,CAAC,IAAI,KAAK,cAAc,EACvC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0JAA0J,CAC3J,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,IAAgB;IACnC,OAAO,MAAM,IAAI,IAAI,CAAC;AACxB,CAAC","sourcesContent":["import {\n ApolloLink,\n ApolloClient as BaseApolloClient,\n DocumentTransform,\n} from \"@apollo/client\";\nimport type {\n WatchQueryOptions,\n ObservableQuery,\n OperationVariables,\n} from \"@apollo/client\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { parse } from \"graphql\";\nimport { equal } from \"@wry/equality\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ApplicationManifest } from \"../../types/application-manifest.js\";\nimport { ToolCallLink } from \"../link/ToolCallLink.js\";\nimport {\n aiClientSymbol,\n cacheAsync,\n getToolNamesFromDocument,\n getVariableNamesFromDocument,\n getVariablesForOperationFromToolInput,\n warnOnVariableMismatch,\n} from \"../../utilities/index.js\";\nimport { McpAppManager } from \"./McpAppManager.js\";\n\nexport declare namespace ApolloClient {\n export interface Options extends Omit<BaseApolloClient.Options, \"link\"> {\n link?: BaseApolloClient.Options[\"link\"];\n manifest: ApplicationManifest;\n }\n}\n\nexport class ApolloClient extends BaseApolloClient {\n manifest: ApplicationManifest;\n private readonly appManager: McpAppManager;\n\n /** @internal */\n readonly [aiClientSymbol] = true;\n\n #toolInput: Record<string, unknown> | undefined;\n\n constructor(options: ApolloClient.Options) {\n const link = options.link ?? new ToolCallLink();\n\n if (__DEV__) {\n validateTerminatingLink(link);\n }\n\n super({\n ...options,\n link,\n // Strip out the prefetch/tool directives so they don't get sent with the operation to the server\n documentTransform: new DocumentTransform((document) => {\n return removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n document\n )!;\n }).concat(options.documentTransform ?? DocumentTransform.identity()),\n });\n\n this.manifest = options.manifest;\n this.appManager = new McpAppManager(this.manifest);\n }\n\n stop() {\n super.stop();\n this.appManager.close().catch(() => {});\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n clearToolInput() {\n this.#toolInput = undefined;\n }\n\n watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {\n if (__DEV__) {\n const toolInput = this.#toolInput;\n\n if (toolInput) {\n const toolName = this.appManager.toolName;\n const hasMatchingTool =\n !!toolName && getToolNamesFromDocument(options.query).has(toolName);\n\n if (hasMatchingTool) {\n // Clear after first matching comparison so this only fires once and\n // remounting doesn't produce spurious warnings.\n this.#toolInput = undefined;\n\n const variableNames = getVariableNamesFromDocument(options.query);\n\n if (variableNames.size > 0) {\n const { variables } = options;\n const toolInputVariables = Object.entries(toolInput).filter(\n ([key]) => variableNames.has(key)\n );\n\n const hasToolInputMismatch = toolInputVariables.some(\n ([key, value]) => !equal(value, variables?.[key])\n );\n\n if (hasToolInputMismatch) {\n warnOnVariableMismatch(\n options.query,\n Object.fromEntries(toolInputVariables),\n variables\n );\n }\n }\n }\n }\n }\n\n return super.watchQuery(options);\n }\n\n connect = cacheAsync(async () => {\n const { prefetch, result, toolName, args } =\n await this.appManager.connect();\n\n this.#toolInput = args;\n\n this.manifest.operations.forEach((operation) => {\n if (operation.prefetchID && prefetch?.[operation.prefetchID]) {\n this.writeQuery({\n query: parse(operation.body),\n data: prefetch[operation.prefetchID].data,\n });\n }\n\n if (operation.tools.find((tool) => tool.name === toolName)) {\n this.writeQuery({\n query: parse(operation.body),\n data: result.data,\n variables: getVariablesForOperationFromToolInput(operation, args),\n });\n }\n });\n });\n}\n\nfunction validateTerminatingLink(link: ApolloLink) {\n let terminatingLink = link;\n\n while (terminatingLink.right) {\n terminatingLink = terminatingLink.right;\n }\n\n if (\n !isNamedLink(terminatingLink) ||\n terminatingLink.name !== \"ToolCallLink\"\n ) {\n throw new Error(\n \"The terminating link must be a `ToolCallLink`. If you are using a `split` link, ensure the `right` branch uses a `ToolCallLink` as the terminating link.\"\n );\n }\n}\n\nfunction isNamedLink(link: ApolloLink): link is ApolloLink & { name: string } {\n return \"name\" in link;\n}\n"]}
1
+ {"version":3,"file":"ApolloClient.js","sourceRoot":"","sources":["../../../src/mcp/core/ApolloClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,YAAY,IAAI,gBAAgB,EAChC,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAMxB,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,sCAAsC,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EACL,cAAc,EACd,UAAU,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,qCAAqC,EACrC,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AASnD,MAAM,OAAO,YAAa,SAAQ,gBAAgB;IAChD,QAAQ,CAAsB;IACb,UAAU,CAAgB;IAE3C,gBAAgB;IACP,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IAEjC,UAAU,CAAsC;IAEhD,YAAY,OAA6B;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,YAAY,EAAE,CAAC;QAEhD,IAAI,OAAO,EAAE,CAAC;YACZ,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAChC,C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,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;YAC7C,IAAI,SAAS,CAAC,UAAU,IAAI,QAAQ,EAAE,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC7D,IAAI,CAAC,UAAU,CAAC;oBACd,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC;oBAC5B,IAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,IAAI;iBAC1C,CAAC,CAAC;YACL,CAAC;YAED,IAAI,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,QAAQ,CAAC,EAAE,CAAC;gBAC3D,IAAI,CAAC,UAAU,CAAC;oBACd,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC;oBAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;oBACjB,SAAS,EAAE,qCAAqC,CAAC,SAAS,EAAE,IAAI,CAAC;iBAClE,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,uBAAuB,CAAC,IAAgB;IAC/C,IAAI,eAAe,GAAG,IAAI,CAAC;IAE3B,OAAO,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,eAAe,GAAG,eAAe,CAAC,KAAK,CAAC;IAC1C,CAAC;IAED,IACE,CAAC,WAAW,CAAC,eAAe,CAAC;QAC7B,eAAe,CAAC,IAAI,KAAK,cAAc,EACvC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0JAA0J,CAC3J,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,IAAgB;IACnC,OAAO,MAAM,IAAI,IAAI,CAAC;AACxB,CAAC","sourcesContent":["import {\n ApolloLink,\n ApolloClient as BaseApolloClient,\n DocumentTransform,\n} from \"@apollo/client\";\nimport type {\n WatchQueryOptions,\n ObservableQuery,\n OperationVariables,\n} from \"@apollo/client\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { parse, visit } from \"graphql\";\nimport { equal } from \"@wry/equality\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ApplicationManifest } from \"../../types/application-manifest.js\";\nimport { ToolCallLink } from \"../link/ToolCallLink.js\";\nimport {\n aiClientSymbol,\n cacheAsync,\n getToolNamesFromDocument,\n getVariableNamesFromDocument,\n getVariablesForOperationFromToolInput,\n warnOnVariableMismatch,\n} from \"../../utilities/index.js\";\nimport { McpAppManager } from \"./McpAppManager.js\";\n\nexport declare namespace ApolloClient {\n export interface Options extends Omit<BaseApolloClient.Options, \"link\"> {\n link?: BaseApolloClient.Options[\"link\"];\n manifest: ApplicationManifest;\n }\n}\n\nexport class ApolloClient extends BaseApolloClient {\n manifest: ApplicationManifest;\n private readonly appManager: McpAppManager;\n\n /** @internal */\n readonly [aiClientSymbol] = true;\n\n #toolInput: Record<string, unknown> | undefined;\n\n constructor(options: ApolloClient.Options) {\n const link = options.link ?? new ToolCallLink();\n\n if (__DEV__) {\n validateTerminatingLink(link);\n }\n\n super({\n ...options,\n link,\n // Strip out the prefetch/tool directives so they don't get sent with the operation to the server\n documentTransform: new DocumentTransform((document) => {\n const serverDocument = removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n document\n )!;\n\n return visit(serverDocument, {\n OperationDefinition(node) {\n return { ...node, description: undefined };\n },\n });\n }).concat(options.documentTransform ?? DocumentTransform.identity()),\n });\n\n this.manifest = options.manifest;\n this.appManager = new McpAppManager(this.manifest);\n }\n\n stop() {\n super.stop();\n this.appManager.close().catch(() => {});\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n clearToolInput() {\n this.#toolInput = undefined;\n }\n\n watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {\n if (__DEV__) {\n const toolInput = this.#toolInput;\n\n if (toolInput) {\n const toolName = this.appManager.toolName;\n const hasMatchingTool =\n !!toolName && getToolNamesFromDocument(options.query).has(toolName);\n\n if (hasMatchingTool) {\n // Clear after first matching comparison so this only fires once and\n // remounting doesn't produce spurious warnings.\n this.#toolInput = undefined;\n\n const variableNames = getVariableNamesFromDocument(options.query);\n\n if (variableNames.size > 0) {\n const { variables } = options;\n const toolInputVariables = Object.entries(toolInput).filter(\n ([key]) => variableNames.has(key)\n );\n\n const hasToolInputMismatch = toolInputVariables.some(\n ([key, value]) => !equal(value, variables?.[key])\n );\n\n if (hasToolInputMismatch) {\n warnOnVariableMismatch(\n options.query,\n Object.fromEntries(toolInputVariables),\n variables\n );\n }\n }\n }\n }\n }\n\n return super.watchQuery(options);\n }\n\n connect = cacheAsync(async () => {\n const { prefetch, result, toolName, args } =\n await this.appManager.connect();\n\n this.#toolInput = args;\n\n this.manifest.operations.forEach((operation) => {\n if (operation.prefetchID && prefetch?.[operation.prefetchID]) {\n this.writeQuery({\n query: parse(operation.body),\n data: prefetch[operation.prefetchID].data,\n });\n }\n\n if (operation.tools.find((tool) => tool.name === toolName)) {\n this.writeQuery({\n query: parse(operation.body),\n data: result.data,\n variables: getVariablesForOperationFromToolInput(operation, args),\n });\n }\n });\n });\n}\n\nfunction validateTerminatingLink(link: ApolloLink) {\n let terminatingLink = link;\n\n while (terminatingLink.right) {\n terminatingLink = terminatingLink.right;\n }\n\n if (\n !isNamedLink(terminatingLink) ||\n terminatingLink.name !== \"ToolCallLink\"\n ) {\n throw new Error(\n \"The terminating link must be a `ToolCallLink`. If you are using a `split` link, ensure the `right` branch uses a `ToolCallLink` as the terminating link.\"\n );\n }\n}\n\nfunction isNamedLink(link: ApolloLink): link is ApolloLink & { name: string } {\n return \"name\" in link;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ApolloClient.d.ts","sourceRoot":"","sources":["../../../src/openai/core/ApolloClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,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C;AAE/E,OAAO,EACL,cAAc,EAKf,MAAM,0BAA0B,CAAC;AAIlC,MAAM,CAAC,OAAO,WAAW,YAAY,CAAC;IACpC,UAAiB,OAAQ,SAAQ,IAAI,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC;QACrE,IAAI,CAAC,EAAE,gBAAgB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACxC,QAAQ,EAAE,mBAAmB,CAAC;KAC/B;CACF;AAED,qBAAa,YAAa,SAAQ,gBAAgB;;IAChD,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAgB;IAE3C,gBAAgB;IAChB,QAAQ,CAAC,CAAC,cAAc,CAAC,QAAQ;gBAIrB,OAAO,EAAE,YAAY,CAAC,OAAO;IA6BzC,IAAI;IAKJ,IAAI,SAAS,wCAEZ;IAED,cAAc;IAId,UAAU,CACR,CAAC,GAAG,GAAG,EACP,UAAU,SAAS,kBAAkB,GAAG,kBAAkB,EAC1D,OAAO,EAAE,iBAAiB,CAAC,UAAU,EAAE,CAAC,CAAC,GAAG,eAAe,CAAC,CAAC,EAAE,UAAU,CAAC;IA0C5E,OAAO;;MAsBJ;CACJ"}
@@ -1,7 +1,7 @@
1
1
  import { ApolloClient as BaseApolloClient } from "@apollo/client";
2
2
  import { DocumentTransform } from "@apollo/client";
3
3
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
4
- import { parse } from "graphql";
4
+ import { parse, visit } from "graphql";
5
5
  import { equal } from "@wry/equality";
6
6
  import { __DEV__ } from "@apollo/client/utilities/environment";
7
7
  import { ToolCallLink } from "../link/ToolCallLink.js";
@@ -24,7 +24,12 @@ export class ApolloClient extends BaseApolloClient {
24
24
  link,
25
25
  // Strip out the prefetch/tool directives so they don't get sent with the operation to the server
26
26
  documentTransform: new DocumentTransform((document) => {
27
- return removeDirectivesFromDocument([{ name: "prefetch" }, { name: "tool" }], document);
27
+ const serverDocument = removeDirectivesFromDocument([{ name: "prefetch" }, { name: "tool" }], document);
28
+ return visit(serverDocument, {
29
+ OperationDefinition(node) {
30
+ return { ...node, description: undefined };
31
+ },
32
+ });
28
33
  }).concat(options.documentTransform ?? DocumentTransform.identity()),
29
34
  });
30
35
  this.manifest = options.manifest;
@@ -1 +1 @@
1
- {"version":3,"file":"ApolloClient.js","sourceRoot":"","sources":["../../../src/openai/core/ApolloClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAMnD,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,sCAAsC,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EACL,cAAc,EACd,UAAU,EACV,wBAAwB,EACxB,qCAAqC,EACrC,sBAAsB,GACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,4BAA4B,EAAE,MAAM,iDAAiD,CAAC;AAS/F,MAAM,OAAO,YAAa,SAAQ,gBAAgB;IAChD,QAAQ,CAAsB;IACb,UAAU,CAAgB;IAE3C,gBAAgB;IACP,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IAEjC,UAAU,CAAsC;IAEhD,YAAY,OAA6B;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,IAAI,YAAY,EAAE,CAAC;QAEhD,IAAI,OAAO,EAAE,CAAC;YACZ,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAChC,CAAC;QAED,KAAK,CAAC;YACJ,GAAG,OAAO;YACV,IAAI;YACJ,iG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EAAE,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,IAAI;iBAC1C,CAAC,CAAC;YACL,CAAC;YAED,IAAI,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,QAAQ,CAAC,EAAE,CAAC;gBAC3D,IAAI,CAAC,UAAU,CAAC;oBACd,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC;oBAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;oBACjB,SAAS,EAAE,qCAAqC,CAAC,SAAS,EAAE,IAAI,CAAC;iBAClE,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,uBAAuB,CAAC,IAAgB;IAC/C,IAAI,eAAe,GAAG,IAAI,CAAC;IAE3B,OAAO,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,eAAe,GAAG,eAAe,CAAC,KAAK,CAAC;IAC1C,CAAC;IAED,IACE,CAAC,WAAW,CAAC,eAAe,CAAC;QAC7B,eAAe,CAAC,IAAI,KAAK,cAAc,EACvC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0JAA0J,CAC3J,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,IAAgB;IACnC,OAAO,MAAM,IAAI,IAAI,CAAC;AACxB,CAAC","sourcesContent":["import type { ApolloLink } from \"@apollo/client\";\nimport { ApolloClient as BaseApolloClient } from \"@apollo/client\";\nimport { DocumentTransform } from \"@apollo/client\";\nimport type {\n WatchQueryOptions,\n ObservableQuery,\n OperationVariables,\n} from \"@apollo/client\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { parse } from \"graphql\";\nimport { equal } from \"@wry/equality\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ApplicationManifest } from \"../../types/application-manifest.js\";\nimport { ToolCallLink } from \"../link/ToolCallLink.js\";\nimport {\n aiClientSymbol,\n cacheAsync,\n getToolNamesFromDocument,\n getVariablesForOperationFromToolInput,\n warnOnVariableMismatch,\n} from \"../../utilities/index.js\";\nimport { McpAppManager } from \"./McpAppManager.js\";\nimport { getVariableNamesFromDocument } from \"../../utilities/getVariableNamesFromDocument.js\";\n\nexport declare namespace ApolloClient {\n export interface Options extends Omit<BaseApolloClient.Options, \"link\"> {\n link?: BaseApolloClient.Options[\"link\"];\n manifest: ApplicationManifest;\n }\n}\n\nexport class ApolloClient extends BaseApolloClient {\n manifest: ApplicationManifest;\n private readonly appManager: McpAppManager;\n\n /** @internal */\n readonly [aiClientSymbol] = true;\n\n #toolInput: Record<string, unknown> | undefined;\n\n constructor(options: ApolloClient.Options) {\n const link = options.link ?? new ToolCallLink();\n\n if (__DEV__) {\n validateTerminatingLink(link);\n }\n\n super({\n ...options,\n link,\n // Strip out the prefetch/tool directives so they don't get sent with the operation to the server\n documentTransform: new DocumentTransform((document) => {\n return removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n document\n )!;\n }).concat(options.documentTransform ?? DocumentTransform.identity()),\n });\n\n this.manifest = options.manifest;\n this.appManager = new McpAppManager(this.manifest);\n }\n\n stop() {\n super.stop();\n this.appManager.close().catch(() => {});\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n clearToolInput() {\n this.#toolInput = undefined;\n }\n\n watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {\n if (__DEV__) {\n const toolInput = this.#toolInput;\n\n if (toolInput) {\n const toolName = this.appManager.toolName;\n const hasMatchingTool =\n !!toolName && getToolNamesFromDocument(options.query).has(toolName);\n\n if (hasMatchingTool) {\n // Clear after first matching comparison so this only fires once and\n // remounting doesn't produce spurious warnings.\n this.#toolInput = undefined;\n\n const variableNames = getVariableNamesFromDocument(options.query);\n\n if (variableNames.size > 0) {\n const { variables } = options;\n\n const toolInputVariables = Object.entries(toolInput).filter(\n ([key]) => variableNames.has(key)\n );\n\n const hasToolInputMismatch = toolInputVariables.some(\n ([key, value]) => !equal(value, variables?.[key])\n );\n\n if (hasToolInputMismatch) {\n warnOnVariableMismatch(\n options.query,\n Object.fromEntries(toolInputVariables),\n variables\n );\n }\n }\n }\n }\n }\n\n return super.watchQuery(options);\n }\n\n connect = cacheAsync(async () => {\n const { prefetch, result, toolName, args } =\n await this.appManager.connect();\n\n this.#toolInput = args;\n\n this.manifest.operations.forEach((operation) => {\n if (operation.prefetchID && prefetch?.[operation.prefetchID]) {\n this.writeQuery({\n query: parse(operation.body),\n data: prefetch[operation.prefetchID].data,\n });\n }\n\n if (operation.tools.find((tool) => tool.name === toolName)) {\n this.writeQuery({\n query: parse(operation.body),\n data: result.data,\n variables: getVariablesForOperationFromToolInput(operation, args),\n });\n }\n });\n });\n}\n\nfunction validateTerminatingLink(link: ApolloLink) {\n let terminatingLink = link;\n\n while (terminatingLink.right) {\n terminatingLink = terminatingLink.right;\n }\n\n if (\n !isNamedLink(terminatingLink) ||\n terminatingLink.name !== \"ToolCallLink\"\n ) {\n throw new Error(\n \"The terminating link must be a `ToolCallLink`. If you are using a `split` link, ensure the `right` branch uses a `ToolCallLink` as the terminating link.\"\n );\n }\n}\n\nfunction isNamedLink(link: ApolloLink): link is ApolloLink & { name: string } {\n return \"name\" in link;\n}\n"]}
1
+ {"version":3,"file":"ApolloClient.js","sourceRoot":"","sources":["../../../src/openai/core/ApolloClient.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAMnD,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;A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qC,CAAC,SAAS,EAAE,IAAI,CAAC;iBAClE,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;CACJ;AAED,SAAS,uBAAuB,CAAC,IAAgB;IAC/C,IAAI,eAAe,GAAG,IAAI,CAAC;IAE3B,OAAO,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,eAAe,GAAG,eAAe,CAAC,KAAK,CAAC;IAC1C,CAAC;IAED,IACE,CAAC,WAAW,CAAC,eAAe,CAAC;QAC7B,eAAe,CAAC,IAAI,KAAK,cAAc,EACvC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,0JAA0J,CAC3J,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,IAAgB;IACnC,OAAO,MAAM,IAAI,IAAI,CAAC;AACxB,CAAC","sourcesContent":["import type { ApolloLink } from \"@apollo/client\";\nimport { ApolloClient as BaseApolloClient } from \"@apollo/client\";\nimport { DocumentTransform } from \"@apollo/client\";\nimport type {\n WatchQueryOptions,\n ObservableQuery,\n OperationVariables,\n} from \"@apollo/client\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { parse, visit } from \"graphql\";\nimport { equal } from \"@wry/equality\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ApplicationManifest } from \"../../types/application-manifest.js\";\nimport { ToolCallLink } from \"../link/ToolCallLink.js\";\nimport {\n aiClientSymbol,\n cacheAsync,\n getToolNamesFromDocument,\n getVariablesForOperationFromToolInput,\n warnOnVariableMismatch,\n} from \"../../utilities/index.js\";\nimport { McpAppManager } from \"./McpAppManager.js\";\nimport { getVariableNamesFromDocument } from \"../../utilities/getVariableNamesFromDocument.js\";\n\nexport declare namespace ApolloClient {\n export interface Options extends Omit<BaseApolloClient.Options, \"link\"> {\n link?: BaseApolloClient.Options[\"link\"];\n manifest: ApplicationManifest;\n }\n}\n\nexport class ApolloClient extends BaseApolloClient {\n manifest: ApplicationManifest;\n private readonly appManager: McpAppManager;\n\n /** @internal */\n readonly [aiClientSymbol] = true;\n\n #toolInput: Record<string, unknown> | undefined;\n\n constructor(options: ApolloClient.Options) {\n const link = options.link ?? new ToolCallLink();\n\n if (__DEV__) {\n validateTerminatingLink(link);\n }\n\n super({\n ...options,\n link,\n // Strip out the prefetch/tool directives so they don't get sent with the operation to the server\n documentTransform: new DocumentTransform((document) => {\n const serverDocument = removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n document\n )!;\n\n return visit(serverDocument, {\n OperationDefinition(node) {\n return { ...node, description: undefined };\n },\n });\n }).concat(options.documentTransform ?? DocumentTransform.identity()),\n });\n\n this.manifest = options.manifest;\n this.appManager = new McpAppManager(this.manifest);\n }\n\n stop() {\n super.stop();\n this.appManager.close().catch(() => {});\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n clearToolInput() {\n this.#toolInput = undefined;\n }\n\n watchQuery<\n T = any,\n TVariables extends OperationVariables = OperationVariables,\n >(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables> {\n if (__DEV__) {\n const toolInput = this.#toolInput;\n\n if (toolInput) {\n const toolName = this.appManager.toolName;\n const hasMatchingTool =\n !!toolName && getToolNamesFromDocument(options.query).has(toolName);\n\n if (hasMatchingTool) {\n // Clear after first matching comparison so this only fires once and\n // remounting doesn't produce spurious warnings.\n this.#toolInput = undefined;\n\n const variableNames = getVariableNamesFromDocument(options.query);\n\n if (variableNames.size > 0) {\n const { variables } = options;\n\n const toolInputVariables = Object.entries(toolInput).filter(\n ([key]) => variableNames.has(key)\n );\n\n const hasToolInputMismatch = toolInputVariables.some(\n ([key, value]) => !equal(value, variables?.[key])\n );\n\n if (hasToolInputMismatch) {\n warnOnVariableMismatch(\n options.query,\n Object.fromEntries(toolInputVariables),\n variables\n );\n }\n }\n }\n }\n }\n\n return super.watchQuery(options);\n }\n\n connect = cacheAsync(async () => {\n const { prefetch, result, toolName, args } =\n await this.appManager.connect();\n\n this.#toolInput = args;\n\n this.manifest.operations.forEach((operation) => {\n if (operation.prefetchID && prefetch?.[operation.prefetchID]) {\n this.writeQuery({\n query: parse(operation.body),\n data: prefetch[operation.prefetchID].data,\n });\n }\n\n if (operation.tools.find((tool) => tool.name === toolName)) {\n this.writeQuery({\n query: parse(operation.body),\n data: result.data,\n variables: getVariablesForOperationFromToolInput(operation, args),\n });\n }\n });\n });\n}\n\nfunction validateTerminatingLink(link: ApolloLink) {\n let terminatingLink = link;\n\n while (terminatingLink.right) {\n terminatingLink = terminatingLink.right;\n }\n\n if (\n !isNamedLink(terminatingLink) ||\n terminatingLink.name !== \"ToolCallLink\"\n ) {\n throw new Error(\n \"The terminating link must be a `ToolCallLink`. If you are using a `split` link, ensure the `right` branch uses a `ToolCallLink` as the terminating link.\"\n );\n }\n}\n\nfunction isNamedLink(link: ApolloLink): link is ApolloLink & { name: string } {\n return \"name\" in link;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"McpAppManager.d.ts","sourceRoot":"","sources":["../../../src/openai/core/McpAppManager.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EAEH,KAAK,mCAAmC,EACzC,MAAM,gCAAgC,CAAC;AAExC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AASvE,gBAAgB;AAChB,qBAAa,aAAa;;IACxB,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;gBAUN,QAAQ,EAAE,mBAAmB;IAIzC,IAAI,QAAQ,uBAEX;IAED,IAAI,YAAY,mCAEf;IAED,IAAI,SAAS,wCAEZ;IAED,oBAAoB,CAClB,EAAE,EAAE,CAAC,MAAM,EAAE,mCAAmC,CAAC,QAAQ,CAAC,KAAK,IAAI;IAQrE,OAAO;;;;;;;MAyCJ;IAEH,KAAK;IAIC,YAAY,CAAC,EACjB,KAAK,EACL,SAAS,GACV,EAAE;QACD,KAAK,EAAE,YAAY,CAAC;QACpB,SAAS,EAAE,kBAAkB,GAAG,SAAS,CAAC;KAC3C;YASa,aAAa;CAW5B"}
1
+ {"version":3,"file":"McpAppManager.d.ts","sourceRoot":"","sources":["../../../src/openai/core/McpAppManager.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EAEH,KAAK,mCAAmC,EACzC,MAAM,gCAAgC,CAAC;AAExC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AASvE,gBAAgB;AAChB,qBAAa,aAAa;;IACxB,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;gBAUN,QAAQ,EAAE,mBAAmB;IAIzC,IAAI,QAAQ,uBAEX;IAED,IAAI,YAAY,mCAEf;IAED,IAAI,SAAS,wCAEZ;IAED,oBAAoB,CAClB,EAAE,EAAE,CAAC,MAAM,EAAE,mCAAmC,CAAC,QAAQ,CAAC,KAAK,IAAI;IAQrE,OAAO;;;;;;;MAoDJ;IAEH,KAAK;IAIC,YAAY,CAAC,EACjB,KAAK,EACL,SAAS,GACV,EAAE;QACD,KAAK,EAAE,YAAY,CAAC;QACpB,SAAS,EAAE,kBAAkB,GAAG,SAAS,CAAC;KAC3C;YASa,aAAa;CAW5B"}
@@ -35,6 +35,16 @@ export class McpAppManager {
35
35
  this.#hostContextCallbacks.forEach((cb) => cb(params));
36
36
  };
37
37
  await this.connectToHost();
38
+ // After a page refresh, OpenAI does not re-send `ui/notifications/tool-result`.
39
+ // Instead, the tool result is available immediately via `window.openai.toolOutput`.
40
+ // If it's already set, resolve the promise now rather than waiting for the
41
+ // notification that will never arrive.
42
+ if (window.openai.toolOutput !== null) {
43
+ toolResult.resolve({
44
+ structuredContent: window.openai.toolOutput,
45
+ content: [],
46
+ });
47
+ }
38
48
  const { structuredContent } = await toolResult.promise;
39
49
  this.#toolName = this.app.getHostContext()?.toolInfo?.tool.name;
40
50
  // OpenAI is not consistent about sending `ui/notifications/tool-input`.
@@ -1 +1 @@
1
- {"version":3,"file":"McpAppManager.js","sourceRoot":"","sources":["../../../src/openai/core/McpAppManager.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,oBAAoB,GAErB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAOnE,gBAAgB;AAChB,MAAM,OAAO,aAAa;IACf,GAAG,CAAM;IAElB,SAAS,CAAqB;IAC9B,aAAa,GAAmC,IAAI,CAAC;IACrD,UAAU,CAAsC;IAEhD,qBAAqB,GAAG,IAAI,GAAG,EAE5B,CAAC;IAEJ,YAAY,QAA6B;QACvC,IAAI,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;IAC5E,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,oBAAoB,CAClB,EAAmE;QAEnE,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACnC,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACxC,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,GAAG,UAAU,C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AM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC;YAC5C,IAAI,EAAE,SAAS;YACf,SAAS,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE;SAC9C,CAAC,CAA+B,CAAC;QAElC,OAAO,MAAM,CAAC,iBAAiB,CAAC;IAClC,CAAC;IAEO,KAAK,CAAC,aAAa;QACzB,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAC3B,IAAI,oBAAoB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CACvD,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,KAAK,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;YAEtE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n App,\n PostMessageTransport,\n type McpUiHostContextChangedNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { ApplicationManifest } from \"../../types/application-manifest\";\nimport type { FormattedExecutionResult } from \"graphql\";\nimport type { DocumentNode, OperationVariables } from \"@apollo/client\";\nimport { print } from \"@apollo/client/utilities\";\nimport { cacheAsync, promiseWithResolvers } from \"../../utilities\";\nimport type { ApolloMcpServerApps } from \"../../core/types\";\n\ntype ExecuteQueryCallToolResult = Omit<CallToolResult, \"structuredContent\"> & {\n structuredContent: FormattedExecutionResult;\n};\n\n/** @internal */\nexport class McpAppManager {\n readonly app: App;\n\n #toolName: string | undefined;\n #toolMetadata: Record<string, unknown> | null = null;\n #toolInput: Record<string, unknown> | undefined;\n\n #hostContextCallbacks = new Set<\n (params: McpUiHostContextChangedNotification[\"params\"]) => void\n >();\n\n constructor(manifest: ApplicationManifest) {\n this.app = new App({ name: manifest.name, version: manifest.appVersion });\n }\n\n get toolName() {\n return this.#toolName;\n }\n\n get toolMetadata() {\n return this.#toolMetadata;\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n onHostContextChanged(\n cb: (params: McpUiHostContextChangedNotification[\"params\"]) => void\n ) {\n this.#hostContextCallbacks.add(cb);\n return () => {\n this.#hostContextCallbacks.delete(cb);\n };\n }\n\n connect = cacheAsync(async () => {\n let toolResult = promiseWithResolvers<ApolloMcpServerApps.CallToolResult>();\n\n this.app.ontoolresult = (params) => {\n toolResult.resolve(\n params as unknown as ApolloMcpServerApps.CallToolResult\n );\n };\n\n this.app.onhostcontextchanged = (params) => {\n this.#hostContextCallbacks.forEach((cb) => cb(params));\n };\n\n await this.connectToHost();\n\n const { structuredContent } = await toolResult.promise;\n\n this.#toolName = this.app.getHostContext()?.toolInfo?.tool.name;\n\n // OpenAI is not consistent about sending `ui/notifications/tool-input`.\n // Sometimes it doesn't send at all, other times it sends more than once\n // before we get the tool result (which should always happen and at most\n // once according to the spec). Rather than relying on the\n // `ui/notifications/tool-input` notification to set the tool input value,\n // we read from `window.openai.toolInput so that we have the most recent\n // set value.\n //\n // When OpenAI fixes this issue and sends `ui/notifications/tool-input`\n // consistently according to the MCP Apps specification, this can be\n // reverted to use the `app.ontoolinput` callback.\n this.#toolInput = window.openai.toolInput;\n\n // OpenAI doesn't provide access to `_meta`, so we need to use\n // window.openai.toolResponseMetadata directly\n this.#toolMetadata = window.openai.toolResponseMetadata;\n\n return {\n ...structuredContent,\n toolName: this.toolName,\n args: this.toolInput,\n };\n });\n\n close() {\n return this.app.close();\n }\n\n async executeQuery({\n query,\n variables,\n }: {\n query: DocumentNode;\n variables: OperationVariables | undefined;\n }) {\n const result = (await this.app.callServerTool({\n name: \"execute\",\n arguments: { query: print(query), variables },\n })) as ExecuteQueryCallToolResult;\n\n return result.structuredContent;\n }\n\n private async connectToHost() {\n try {\n return await this.app.connect(\n new PostMessageTransport(window.parent, window.parent)\n );\n } catch (e) {\n const error = e instanceof Error ? e : new Error(\"Failed to connect\");\n\n throw error;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"McpAppManager.js","sourceRoot":"","sources":["../../../src/openai/core/McpAppManager.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,oBAAoB,GAErB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAOnE,gBAAgB;AAChB,MAAM,OAAO,aAAa;IACf,GAAG,CAAM;IAElB,SAAS,CAAqB;IAC9B,aAAa,GAAmC,IAAI,CAAC;IACrD,UAAU,CAAsC;IAEhD,qBAAqB,GAAG,IAAI,GAAG,EAE5B,CAAC;IAEJ,YAAY,QAA6B;QACvC,IAAI,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;IAC5E,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,oBAAoB,CAClB,EAAmE;QAEnE,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACnC,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACxC,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,GAAG,UAAU,CAAC,KAAK,IAAI,EAAE;QAC9B,IAAI,UAAU,GAAG,oBAAoB,EAAsC,CAAC;QAE5E,IAAI,CAAC,GAAG,CAAC,YAAY,GA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C,CAAC;IAEH,KAAK;QACH,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,EACjB,KAAK,EACL,SAAS,GAIV;QACC,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC;YAC5C,IAAI,EAAE,SAAS;YACf,SAAS,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,SAAS,EAAE;SAC9C,CAAC,CAA+B,CAAC;QAElC,OAAO,MAAM,CAAC,iBAAiB,CAAC;IAClC,CAAC;IAEO,KAAK,CAAC,aAAa;QACzB,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAC3B,IAAI,oBAAoB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CACvD,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,KAAK,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;YAEtE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n App,\n PostMessageTransport,\n type McpUiHostContextChangedNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport type { CallToolResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { ApplicationManifest } from \"../../types/application-manifest\";\nimport type { FormattedExecutionResult } from \"graphql\";\nimport type { DocumentNode, OperationVariables } from \"@apollo/client\";\nimport { print } from \"@apollo/client/utilities\";\nimport { cacheAsync, promiseWithResolvers } from \"../../utilities\";\nimport type { ApolloMcpServerApps } from \"../../core/types\";\n\ntype ExecuteQueryCallToolResult = Omit<CallToolResult, \"structuredContent\"> & {\n structuredContent: FormattedExecutionResult;\n};\n\n/** @internal */\nexport class McpAppManager {\n readonly app: App;\n\n #toolName: string | undefined;\n #toolMetadata: Record<string, unknown> | null = null;\n #toolInput: Record<string, unknown> | undefined;\n\n #hostContextCallbacks = new Set<\n (params: McpUiHostContextChangedNotification[\"params\"]) => void\n >();\n\n constructor(manifest: ApplicationManifest) {\n this.app = new App({ name: manifest.name, version: manifest.appVersion });\n }\n\n get toolName() {\n return this.#toolName;\n }\n\n get toolMetadata() {\n return this.#toolMetadata;\n }\n\n get toolInput() {\n return this.#toolInput;\n }\n\n onHostContextChanged(\n cb: (params: McpUiHostContextChangedNotification[\"params\"]) => void\n ) {\n this.#hostContextCallbacks.add(cb);\n return () => {\n this.#hostContextCallbacks.delete(cb);\n };\n }\n\n connect = cacheAsync(async () => {\n let toolResult = promiseWithResolvers<ApolloMcpServerApps.CallToolResult>();\n\n this.app.ontoolresult = (params) => {\n toolResult.resolve(\n params as unknown as ApolloMcpServerApps.CallToolResult\n );\n };\n\n this.app.onhostcontextchanged = (params) => {\n this.#hostContextCallbacks.forEach((cb) => cb(params));\n };\n\n await this.connectToHost();\n\n // After a page refresh, OpenAI does not re-send `ui/notifications/tool-result`.\n // Instead, the tool result is available immediately via `window.openai.toolOutput`.\n // If it's already set, resolve the promise now rather than waiting for the\n // notification that will never arrive.\n if (window.openai.toolOutput !== null) {\n toolResult.resolve({\n structuredContent: window.openai.toolOutput,\n content: [],\n });\n }\n\n const { structuredContent } = await toolResult.promise;\n\n this.#toolName = this.app.getHostContext()?.toolInfo?.tool.name;\n\n // OpenAI is not consistent about sending `ui/notifications/tool-input`.\n // Sometimes it doesn't send at all, other times it sends more than once\n // before we get the tool result (which should always happen and at most\n // once according to the spec). Rather than relying on the\n // `ui/notifications/tool-input` notification to set the tool input value,\n // we read from `window.openai.toolInput so that we have the most recent\n // set value.\n //\n // When OpenAI fixes this issue and sends `ui/notifications/tool-input`\n // consistently according to the MCP Apps specification, this can be\n // reverted to use the `app.ontoolinput` callback.\n this.#toolInput = window.openai.toolInput;\n\n // OpenAI doesn't provide access to `_meta`, so we need to use\n // window.openai.toolResponseMetadata directly\n this.#toolMetadata = window.openai.toolResponseMetadata;\n\n return {\n ...structuredContent,\n toolName: this.toolName,\n args: this.toolInput,\n };\n });\n\n close() {\n return this.app.close();\n }\n\n async executeQuery({\n query,\n variables,\n }: {\n query: DocumentNode;\n variables: OperationVariables | undefined;\n }) {\n const result = (await this.app.callServerTool({\n name: \"execute\",\n arguments: { query: print(query), variables },\n })) as ExecuteQueryCallToolResult;\n\n return result.structuredContent;\n }\n\n private async connectToHost() {\n try {\n return await this.app.connect(\n new PostMessageTransport(window.parent, window.parent)\n );\n } catch (e) {\n const error = e instanceof Error ? e : new Error(\"Failed to connect\");\n\n throw error;\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"apolloClientAiApps.d.ts","sourceRoot":"","sources":["../../src/vite/apolloClientAiApps.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,MAAM,EAEZ,MAAM,MAAM,CAAC;AAMd,OAAO,EAA4B,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAqB7E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAenE,MAAM,CAAC,OAAO,WAAW,kBAAkB,CAAC;IAC1C,KAAY,MAAM,GAAG,wBAAwB,CAAC,SAAS,CAAC;IAExD,UAAiB,OAAO;QACtB,OAAO,EAAE,MAAM,EAAE,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;KAC7B;CACF;AAgBD,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,gCAOnD;AA+TD,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,kBAAkB,CAAC,OAAO,GAClC,MAAM,CAoZR;AA0GD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,YAAY,CA2CzE"}
1
+ {"version":3,"file":"apolloClientAiApps.d.ts","sourceRoot":"","sources":["../../src/vite/apolloClientAiApps.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,MAAM,EAEZ,MAAM,MAAM,CAAC;AAMd,OAAO,EAA4B,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAqB7E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAenE,MAAM,CAAC,OAAO,WAAW,kBAAkB,CAAC;IAC1C,KAAY,MAAM,GAAG,wBAAwB,CAAC,SAAS,CAAC;IAExD,UAAiB,OAAO;QACtB,OAAO,EAAE,MAAM,EAAE,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;KAC7B;CACF;AAgBD,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,gCAOnD;AA+TD,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,kBAAkB,CAAC,OAAO,GAClC,MAAM,CAoZR;AAoHD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,YAAY,GAAG,YAAY,CA2CzE"}
@@ -12,7 +12,7 @@ import { glob } from "glob";
12
12
  import { print } from "@apollo/client/utilities";
13
13
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
14
14
  import { of } from "rxjs";
15
- import { Kind, OperationTypeNode, parse } from "graphql";
15
+ import { Kind, OperationTypeNode, parse, visit } from "graphql";
16
16
  import { getArgumentValue, getDirectiveArgument, getTypeName, maybeGetArgumentValue, } from "./utilities/graphql.js";
17
17
  import { invariant } from "../utilities/invariant.js";
18
18
  import { explorer } from "./utilities/config.js";
@@ -504,7 +504,7 @@ export function apolloClientAiApps(options) {
504
504
  };
505
505
  }
506
506
  const processQueryLink = new ApolloLink((operation) => {
507
- const body = print(removeManifestDirectives(sortTopLevelDefinitions(operation.query)));
507
+ const body = print(removeOperationDescription(removeManifestDirectives(sortTopLevelDefinitions(operation.query))));
508
508
  const name = operation.operationName;
509
509
  const definition = operation.query.definitions.find((d) => d.kind === "OperationDefinition");
510
510
  // Use `operation.query` so that the error reflects the end-user defined
@@ -558,6 +558,13 @@ const processQueryLink = new ApolloLink((operation) => {
558
558
  data: { id, name, type, body, variables, prefetch, prefetchID, tools },
559
559
  });
560
560
  });
561
+ function removeOperationDescription(doc) {
562
+ return visit(doc, {
563
+ OperationDefinition(node) {
564
+ return { ...node, description: undefined };
565
+ },
566
+ });
567
+ }
561
568
  function removeManifestDirectives(doc) {
562
569
  return removeDirectivesFromDocument([{ name: "prefetch" }, { name: "tool" }], doc);
563
570
  }
@@ -1 +1 @@
1
- {"version":3,"file":"apolloClientAiApps.js","sourceRoot":"","sources":["../../src/vite/apolloClientAiApps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,gBAAgB,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,UAAU,EAAqB,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,0BAA0B,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,OAAO,EAAE,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AE;IACvB,WAAW,EAAE,CAAC,CAAC,QAAQ,CACrB,CAAC,CAAC,KAAK,CACL,CAAC,CAAC,YAAY,CAAC;QACb,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;QAChB,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE;QACvB,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;KACjD,CAAC,CACH,CACF;IACD,MAAM,EAAE,8BAA8B,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE;CAC/D,CAAC,CAAC","sourcesContent":["import {\n defaultClientConditions,\n type Plugin,\n type ResolvedConfig,\n} from \"vite\";\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport * as recast from \"recast\";\nimport typescriptParser from \"recast/parsers/typescript.js\";\nimport { ApolloClient, ApolloLink, type DocumentNode } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client\";\nimport { equal } from \"@wry/equality\";\nimport { gqlPluckFromCodeStringSync } from \"@graphql-tools/graphql-tag-pluck\";\nimport { glob } from \"glob\";\nimport { print } from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { of } from \"rxjs\";\nimport { Kind, OperationTypeNode, parse } from \"graphql\";\nimport {\n getArgumentValue,\n getDirectiveArgument,\n getTypeName,\n maybeGetArgumentValue,\n} from \"./utilities/graphql.js\";\nimport type {\n ApplicationManifest,\n ManifestOperation,\n} from \"../types/application-manifest\";\nimport { invariant } from \"../utilities/invariant.js\";\nimport { explorer } from \"./utilities/config.js\";\nimport type { ApolloClientAiAppsConfig } from \"../config/index.js\";\nimport { ApolloClientAiAppsConfigSchema } from \"../config/schema.js\";\nimport { z } from \"zod\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\nimport {\n buildImportStatement,\n buildPropertySignature,\n buildKeywordLiteral,\n printRecast,\n type TSInterfaceBody,\n} from \"./utilities/recast.js\";\nimport type { TypeScriptDocumentsPluginConfig } from \"@graphql-codegen/typescript-operations\";\n\nconst b = recast.types.builders;\n\nexport declare namespace apolloClientAiApps {\n export type Target = ApolloClientAiAppsConfig.AppTarget;\n\n export interface Options {\n targets: Target[];\n devTarget?: Target | undefined;\n appsOutDir: string;\n schema?: string | undefined;\n }\n}\n\nconst root = process.cwd();\n\nconst VALID_TARGETS: apolloClientAiApps.Target[] = [\"openai\", \"mcp\"];\n\nfunction isValidTarget(target: unknown): target is apolloClientAiApps.Target {\n return VALID_TARGETS.includes(target as apolloClientAiApps.Target);\n}\n\nfunction buildExtensions(target: apolloClientAiApps.Target) {\n return [\".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"].flatMap(\n (ext) => [`.${target}${ext}`, ext]\n );\n}\n\nexport function devTarget(target: string | undefined) {\n invariant(\n target === undefined || isValidTarget(target),\n `devTarget '${target}' is not a valid dev target. Must be one of ${VALID_TARGETS.join(\", \")}.`\n );\n\n return target;\n}\n\ninterface FileCache {\n hash: string;\n sources: DocumentNode[];\n}\n\nfunction md5(contents: string) {\n return createHash(\"md5\").update(contents).digest(\"hex\");\n}\n\n/**\n * Builds the AST for the comment used at the top of a generated file from this\n * plugin.\n *\n * @remarks\n * This comment informs users that generated files from this plugin should not\n * be edited since it is autogenerated by this plugin.\n */\nfunction buildHeaderComment() {\n return b.commentLine(\n \" This file is auto-generated by @apollo/client-ai-apps. Do not edit manually.\",\n true,\n false\n );\n}\n\n/**\n * Builds the `@apollo/client-ai-apps` ambient module declaration for the\n * `register.d.ts` file.\n *\n * @param registerInterfaceBody - The interface body for the `Register`\n * interface\n *\n * @example\n * ```ts\n * buildAmbientModuleDeclaration(interfaceBody);\n * // =>\n * // declare namespace \"@apollo/client-ai-apps\" {\n * // interface Register {\n * // // ...interfaceBody\n * // }\n * // }\n * ```\n */\nfunction buildAmbientModuleDeclaration(registerInterfaceBody: TSInterfaceBody) {\n const interfaceDeclaration = b.tsInterfaceDeclaration(\n b.identifier(\"Register\"),\n b.tsInterfaceBody(registerInterfaceBody)\n );\n\n const moduleDeclaration = b.tsModuleDeclaration(\n b.stringLiteral(\"@apollo/client-ai-apps\"),\n b.tsModuleBlock([interfaceDeclaration])\n );\n moduleDeclaration.declare = true;\n\n return moduleDeclaration;\n}\n\n/**\n * Gets the variables type name for an operation. GraphQL Codegen creates\n * variables types with the combination of operationName + operationType +\n * \"Variables\"\n *\n * @example\n * ```ts\n * getVariablesTypeName({ name: \"GetProduct\", type: \"query\" });\n * // => \"GetProductQueryVariables\"\n * ````\n */\nfunction getVariablesTypeName(operation: ManifestOperation) {\n const { name, type } = operation;\n\n return `${name}${type.charAt(0).toUpperCase()}${type.slice(1)}Variables`;\n}\n\n/**\n * Returns the code string written to the `.apollo-client-ai-apps/types/register.d.ts` files\n * for a given set of operations.\n */\nfunction getRegisteredTypeContents({\n operations,\n schema,\n flagSchemaBuildError = false,\n}: {\n operations: ManifestOperation[];\n schema: string | undefined;\n /**\n * Used during dev to avoid failing the build and instead output the error\n * to the console. When providing an error, the error message is generated as\n * a literal type value in the `register.d.ts` file so that users can see the\n * error message when hovering over the type.\n */\n flagSchemaBuildError?: false | Error;\n}) {\n if (flagSchemaBuildError) {\n const message = `[@apollo/client-ai-apps/vite]: There was an error building generated types. See the vite build output for more details.\\n\\n${flagSchemaBuildError.message}`;\n\n const importBaseStatement = buildImportStatement(\n [],\n \"@apollo/client-ai-apps\"\n );\n importBaseStatement.comments = [buildHeaderComment()];\n\n const typeAnnotation = b.tsLiteralType(b.stringLiteral(message));\n\n return printRecast(\n b.program([\n importBaseStatement,\n buildAmbientModuleDeclaration([\n buildPropertySignature(\"toolName\", typeAnnotation),\n buildPropertySignature(\n \"toolInputs\",\n b.tsTypeLiteral([buildPropertySignature(message, typeAnnotation)])\n ),\n ]),\n ])\n );\n }\n\n const toolNames = operations.flatMap((op) => op.tools.map((t) => t.name));\n\n if (toolNames.length === 0) {\n const emptyExport = b.exportNamedDeclaration(null);\n emptyExport.comments = [buildHeaderComment()];\n return printRecast(b.program([emptyExport]));\n }\n\n const importBaseStatement = buildImportStatement(\n [],\n \"@apollo/client-ai-apps\"\n );\n importBaseStatement.comments = [buildHeaderComment()];\n\n const toolNameProp = buildPropertySignature(\n \"toolName\",\n b.tsUnionType(toolNames.map((n) => b.tsLiteralType(b.stringLiteral(n))))\n );\n\n if (!schema) {\n return printRecast(\n b.program([\n importBaseStatement,\n buildAmbientModuleDeclaration([toolNameProp]),\n ])\n );\n }\n\n const importedVariableTypes = new Set<string>();\n const toolInputsValue: recast.types.namedTypes.TSPropertySignature[] = [];\n\n for (const operation of operations) {\n const variablesTypeName = getVariablesTypeName(operation);\n\n if (operation.tools.length) {\n importedVariableTypes.add(variablesTypeName);\n }\n\n for (const tool of operation.tools) {\n const variablesTypeRef = b.tsTypeReference(\n b.identifier(variablesTypeName)\n );\n let typeExpression:\n | recast.types.namedTypes.TSTypeReference\n | recast.types.namedTypes.TSIntersectionType = variablesTypeRef;\n\n if (tool.extraInputs?.length) {\n const extraInputsType = tool.extraInputs.map((ei) => {\n return buildPropertySignature(\n ei.name,\n buildKeywordLiteral(ei.type),\n true\n );\n });\n\n typeExpression = b.tsIntersectionType([\n variablesTypeRef,\n b.tsTypeLiteral(extraInputsType),\n ]);\n }\n\n toolInputsValue.push(buildPropertySignature(tool.name, typeExpression));\n }\n }\n\n return printRecast(\n b.program([\n importBaseStatement,\n buildImportStatement(\n Array.from(importedVariableTypes),\n \"./operation-types.js\",\n \"type\"\n ),\n buildAmbientModuleDeclaration([\n toolNameProp,\n buildPropertySignature(\"toolInputs\", b.tsTypeLiteral(toolInputsValue)),\n ]),\n ])\n );\n}\n\n/**\n * Generates and returns the code string written to the\n * `.apollo-client-ai-apps/types/operation-types.d.ts` file. Uses GraphQL\n * Codegen to introspect the given schema and extract variable types.\n */\nasync function generateOperationTypes(\n schema: string,\n documents: string[]\n): Promise<string> {\n const { generate } = await import(\"@graphql-codegen/cli\");\n\n if (documents.length === 0) {\n return `// Auto-generated by @apollo/client-ai-apps. Do not edit manually.\\nexport {};\\n`;\n }\n\n const output = await generate(\n {\n schema,\n documents,\n generates: {\n \"operation-types.d.ts\": {\n plugins: [\"typescript\", \"typescript-operations\"],\n config: {\n nonOptionalTypename: true,\n skipTypeNameForRoot: true,\n } satisfies TypeScriptDocumentsPluginConfig,\n },\n },\n silent: true,\n } as Parameters<typeof generate>[0],\n false\n );\n\n const content = (output as { filename: string; content: string }[])[0]\n .content;\n return `// Auto-generated by @apollo/client-ai-apps. Do not edit manually.\\n${content}`;\n}\n\n/**\n * Gets the name of an exported type (e.g. `export type x`) from a TypeScript\n * AST statement.\n */\nfunction getExportedTypeAliasName(\n statement: recast.types.namedTypes.Statement\n): string | undefined {\n if (statement.type !== \"ExportNamedDeclaration\") return;\n\n const declaration = (\n statement as recast.types.namedTypes.ExportNamedDeclaration\n ).declaration;\n\n if (!declaration || declaration.type !== \"TSTypeAliasDeclaration\") return;\n\n const alias = declaration as recast.types.namedTypes.TSTypeAliasDeclaration;\n return typeof alias.id.name === \"string\" ? alias.id.name : undefined;\n}\n\n/**\n * Removes all non-`*Variables` types from the `operation-types.d.ts` file.\n * The `typescript` and `typescript-operations` codegen plugins add full schema\n * types and operation types. This function ensures those unused types are\n * removed.\n */\nfunction filterOperationTypes(\n content: string,\n rootTypeNames: Set<string>\n): string {\n const ast = recast.parse(content, { parser: typescriptParser });\n const statements: recast.types.namedTypes.Statement[] = ast.program.body;\n const typeMap = new Map<\n string,\n recast.types.namedTypes.TSTypeAliasDeclaration\n >();\n\n for (const statement of statements) {\n const name = getExportedTypeAliasName(statement);\n\n if (name) {\n typeMap.set(\n name,\n (statement as recast.types.namedTypes.ExportNamedDeclaration)\n .declaration as recast.types.namedTypes.TSTypeAliasDeclaration\n );\n }\n }\n\n const reachable = new Set<string>(rootTypeNames);\n const queue = Array.from(rootTypeNames);\n\n while (queue.length > 0) {\n const name = queue.shift()!;\n const node = typeMap.get(name);\n\n if (!node) continue;\n\n recast.visit(node, {\n visitTSTypeReference(path) {\n const typeName = path.value.typeName?.name as string | undefined;\n\n if (typeName && !reachable.has(typeName)) {\n reachable.add(typeName);\n queue.push(typeName);\n }\n\n this.traverse(path);\n },\n });\n }\n\n ast.program.body = statements.filter((statement) => {\n const name = getExportedTypeAliasName(statement);\n return name === undefined || reachable.has(name);\n });\n\n return printRecast(ast);\n}\n\nexport function apolloClientAiApps(\n options: apolloClientAiApps.Options\n): Plugin {\n const targets = Array.from(new Set(options.targets));\n const {\n devTarget = targets.length === 1 ? targets[0] : undefined,\n appsOutDir,\n schema,\n } = options;\n let config!: ResolvedConfig;\n\n const fragments = createFragmentRegistry();\n\n invariant(\n Array.isArray(targets) && targets.length > 0,\n \"The `targets` option must be a non-empty array\"\n );\n\n invariant(\n targets.every(isValidTarget),\n `All targets must be one of: ${VALID_TARGETS.join(\", \")}`\n );\n\n invariant(\n path.basename(path.normalize(appsOutDir)) === \"apps\",\n \"`appsOutDir` must end with `apps` as the final path segment (e.g. `path/to/apps`).\"\n );\n\n const client = new ApolloClient({\n cache: new InMemoryCache({ fragments }),\n link: processQueryLink,\n });\n\n let sources: DocumentNode[] = [];\n\n function recomputeSources(cache: Map<string, FileCache>) {\n sources = Array.from(cache.values()).flatMap((entry) => entry.sources);\n }\n\n async function getManifestOperations() {\n if (sources === getManifestOperations.cache.sources) {\n return getManifestOperations.cache.manifestOperations;\n }\n\n const manifestOperations = [];\n for (const source of sources) {\n const operationDef = source.definitions.find(\n (d) => d.kind === Kind.OPERATION_DEFINITION\n );\n\n if (!operationDef) continue;\n\n switch (operationDef.operation) {\n case OperationTypeNode.QUERY: {\n const result = await client.query<ManifestOperation>({\n query: source,\n fetchPolicy: \"no-cache\",\n });\n\n manifestOperations.push(result.data!);\n break;\n }\n case OperationTypeNode.MUTATION: {\n const result = await client.mutate<ManifestOperation>({\n mutation: source,\n fetchPolicy: \"no-cache\",\n });\n\n manifestOperations.push(result.data!);\n break;\n }\n default:\n throw new Error(\n `Found unsupported operation type '${operationDef.operation}'. Only queries and mutations are supported.`\n );\n }\n }\n\n getManifestOperations.cache = { sources, manifestOperations };\n\n return manifestOperations;\n }\n\n getManifestOperations.cache = {\n sources,\n manifestOperations: [] as ManifestOperation[],\n };\n\n async function processFile(file: string) {\n const code = fs.readFileSync(file, \"utf-8\");\n\n if (!code.includes(\"gql\")) return;\n\n const fileHash = md5(code);\n if (processFile.cache.get(file)?.hash === fileHash) return;\n\n const sources = gqlPluckFromCodeStringSync(file, code, {\n modules: [\n { name: \"graphql-tag\", identifier: \"gql\" },\n { name: \"@apollo/client\", identifier: \"gql\" },\n ],\n }).map((source) => parse(source.body));\n\n const previousSources = processFile.cache.get(file)?.sources;\n\n if (previousSources && equal(sources, previousSources)) {\n processFile.cache.set(file, { hash: fileHash, sources: previousSources });\n return;\n }\n\n fragments.register(...sources);\n\n processFile.cache.set(file, { hash: fileHash, sources });\n recomputeSources(processFile.cache);\n }\n\n processFile.cache = new Map<string, FileCache>();\n\n async function generateManifest() {\n const appsConfig = await getAppsConfig();\n const operations = await getManifestOperations();\n\n invariant(\n operations.filter((o) => o.prefetch).length <= 1,\n \"Found multiple operations marked as `@prefetch`. You can only mark 1 operation with `@prefetch`.\"\n );\n\n function getBuildResourceForTarget(target: apolloClientAiApps.Target) {\n const entryPoint = getResourceFromConfig(appsConfig, config.mode, target);\n\n if (entryPoint) {\n return entryPoint;\n }\n\n if (config.mode === \"production\") {\n return `${target}/index.html`;\n }\n\n throw new Error(\n `No entry point found for mode \"${config.mode}\". Entry points other than \"development\" and \"production\" must be defined in package.json file.`\n );\n }\n\n let resource: ApplicationManifest[\"resource\"];\n if (config.command === \"serve\") {\n // Dev mode: resource is a string (dev server URL)\n resource =\n getResourceFromConfig(appsConfig, config.mode, devTarget!) ??\n `http${config.server.https ? \"s\" : \"\"}://${config.server.host ?? \"localhost\"}:${config.server.port}`;\n } else {\n resource = Object.fromEntries(\n targets.map((target) => [target, getBuildResourceForTarget(target)])\n ) as { mcp?: string; openai?: string };\n }\n\n const packageJson = readPackageJson();\n const appName = appsConfig.name ?? packageJson.name;\n\n invariant(\n appName,\n \"Error generating application manifest. Could not determine app name. Set `name` in your apollo-client-ai-apps config or `package.json`.\"\n );\n\n const manifest: ApplicationManifest = {\n format: \"apollo-ai-app-manifest\",\n version: \"1\",\n appVersion: appsConfig.version ?? packageJson.version,\n name: appsConfig.name ?? packageJson.name,\n description: appsConfig.description ?? packageJson.description,\n hash: createHash(\"sha256\").update(Date.now().toString()).digest(\"hex\"),\n operations,\n resource,\n csp: {\n baseUriDomains: appsConfig.csp?.baseUriDomains ?? [],\n connectDomains: appsConfig.csp?.connectDomains ?? [],\n frameDomains: appsConfig.csp?.frameDomains ?? [],\n redirectDomains: appsConfig.csp?.redirectDomains ?? [],\n resourceDomains: appsConfig.csp?.resourceDomains ?? [],\n },\n };\n\n if (isNonEmptyObject(appsConfig.widgetSettings)) {\n manifest.widgetSettings = appsConfig.widgetSettings;\n }\n\n if (isNonEmptyObject(appsConfig.labels)) {\n manifest.labels = appsConfig.labels;\n }\n\n const manifestContents = JSON.stringify(manifest);\n\n // Always write to build directory so the MCP server picks it up\n writeFileSync(\n path.resolve(root, appsOutDir, appName, \".application-manifest.json\"),\n manifestContents\n );\n\n // Always write to the dev location so that the app can bundle the manifest content\n writeFileSync(\".application-manifest.json\", manifestContents);\n\n const manifestTypesFilepath = \".application-manifest.d.json.ts\";\n if (!fs.existsSync(manifestTypesFilepath)) {\n const manifestImport = b.importDeclaration(\n [b.importSpecifier(b.identifier(\"ApplicationManifest\"))],\n b.stringLiteral(\"@apollo/client-ai-apps\"),\n \"type\"\n );\n const manifestId = b.identifier(\"manifest\");\n manifestId.typeAnnotation = b.tsTypeAnnotation(\n b.tsTypeReference(b.identifier(\"ApplicationManifest\"), null)\n );\n const manifestDeclaration = b.variableDeclaration(\"const\", [\n b.variableDeclarator(manifestId, null),\n ]) as recast.types.namedTypes.VariableDeclaration & { declare: boolean };\n manifestDeclaration.declare = true;\n\n const exportDefault = b.exportDefaultDeclaration(\n b.identifier(\"manifest\")\n );\n\n const content = printRecast(\n b.program([manifestImport, manifestDeclaration, exportDefault])\n );\n\n writeFileSync(manifestTypesFilepath, content);\n }\n }\n\n async function generateTypesFiles() {\n let flagSchemaBuildError: false | Error = false;\n const operations = await getManifestOperations();\n\n if (operations === generateTypesFiles.cache) {\n return;\n }\n\n generateTypesFiles.cache = operations;\n\n if (schema) {\n try {\n const opTypesContent = await generateOperationTypes(\n schema,\n operations.map((op) => op.body)\n );\n\n const rootTypeNames = new Set(\n operations.flatMap((op) =>\n op.tools.length > 0 ? [getVariablesTypeName(op)] : []\n )\n );\n\n writeFileSync(\n path.resolve(\n root,\n \".apollo-client-ai-apps/types/operation-types.d.ts\"\n ),\n filterOperationTypes(opTypesContent, rootTypeNames),\n { cache: true }\n );\n } catch (e) {\n if (config.command === \"build\") {\n throw e;\n }\n\n flagSchemaBuildError = e as Error;\n console.error(\"[@apollo/client-ai-apps/vite]:\", e);\n }\n }\n\n const typesFileContents = getRegisteredTypeContents({\n operations,\n schema,\n flagSchemaBuildError,\n });\n\n writeFileSync(\n path.resolve(root, \".apollo-client-ai-apps/types/register.d.ts\"),\n typesFileContents,\n { cache: true }\n );\n }\n\n generateTypesFiles.cache = [] as ManifestOperation[] | undefined;\n\n return {\n name: \"@apollo/client-ai-apps/vite\",\n async buildStart() {\n // Scan all files on startup\n const files = await glob(\"./src/**/*.{ts,tsx,js,jsx}\", { fs });\n\n for (const file of files) {\n const fullPath = path.resolve(root, file);\n await processFile(fullPath);\n }\n\n // We don't want to do this here on builds cause it just gets overwritten anyways. We'll call it on writeBundle instead.\n if (config.command === \"serve\") {\n await Promise.all([generateManifest(), generateTypesFiles()]);\n }\n },\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n async configEnvironment(name) {\n if (!targets.includes(name as any)) return;\n\n const appsConfig = await getAppsConfig();\n const appName = appsConfig.name ?? readPackageJson().name;\n\n invariant(\n appName,\n \"Could not determine app name. Set `name` in your apollo-client-ai-apps config or `package.json`.\"\n );\n\n return {\n build: {\n outDir: path.join(appsOutDir, appName, name),\n },\n };\n },\n configureServer(server) {\n server.watcher.on(\"change\", async (file) => {\n if (file.endsWith(\"package.json\")) {\n readPackageJson.resetCache();\n await generateManifest();\n } else if (file.match(/\\.?apollo-client-ai-apps\\.config\\.\\w+$/)) {\n explorer.clearCaches();\n await generateManifest();\n } else if (file.match(/\\.(jsx?|tsx?)$/)) {\n await processFile(file);\n await Promise.all([generateManifest(), generateTypesFiles()]);\n }\n });\n },\n\n config(userConfig, { command }) {\n if (userConfig.build?.outDir) {\n console.warn(\n \"[@apollo/client-ai-apps/vite] `build.outDir` is set in your Vite config but will be \" +\n \"ignored. Use `appsOutDir` in the plugin options to control the output location.\"\n );\n }\n\n if (command === \"serve\") {\n invariant(\n isValidTarget(devTarget) || targets.length === 1,\n \"`devTarget` must be set for development when using multiple targets.\"\n );\n\n const target = devTarget ?? targets[0];\n\n return {\n resolve: {\n extensions: buildExtensions(target),\n conditions: [target, ...defaultClientConditions],\n },\n };\n }\n\n return {\n environments: Object.fromEntries(\n targets.map((target) => [\n target,\n {\n consumer: \"client\",\n webCompatible: true,\n resolve: {\n extensions: buildExtensions(target),\n conditions: [target, ...defaultClientConditions],\n },\n },\n ])\n ),\n builder: {\n buildApp: async (builder) => {\n await Promise.all(\n targets.map((target) =>\n builder.build(builder.environments[target])\n )\n );\n },\n },\n };\n },\n transformIndexHtml(html, ctx) {\n if (!ctx.server) return html;\n\n let baseUrl = (\n ctx.server.config?.server?.origin ??\n ctx.server.resolvedUrls?.local[0] ??\n \"\"\n ).replace(/\\/$/, \"\");\n baseUrl = baseUrl.replace(/\\/$/, \"\");\n\n return (\n html\n // import \"/@vite/...\" or \"/@react-refresh\"\n .replace(/(from\\s+[\"'])\\/([^\"']+)/g, `$1${baseUrl}/$2`)\n // src=\"/src/...\"\n .replace(/(src=[\"'])\\/([^\"']+)/gi, `$1${baseUrl}/$2`)\n );\n },\n async writeBundle() {\n await Promise.all([generateManifest(), generateTypesFiles()]);\n },\n } satisfies Plugin;\n}\n\nconst processQueryLink = new ApolloLink((operation) => {\n const body = print(\n removeManifestDirectives(sortTopLevelDefinitions(operation.query))\n );\n const name = operation.operationName;\n const definition = operation.query.definitions.find(\n (d) => d.kind === \"OperationDefinition\"\n );\n\n // Use `operation.query` so that the error reflects the end-user defined\n // document, not our sorted one\n invariant(\n definition,\n `Document does not contain an operation:\\n${print(operation.query)}`\n );\n\n const { directives, operation: type } = definition;\n\n const variables = definition.variableDefinitions?.reduce(\n (obj, varDef) => ({\n ...obj,\n [varDef.variable.name.value]: getTypeName(varDef.type),\n }),\n {}\n );\n\n const prefetch = directives?.some((d) => d.name.value === \"prefetch\");\n const id = createHash(\"sha256\").update(body).digest(\"hex\");\n // TODO: For now, you can only have 1 operation marked as prefetch. In the future, we'll likely support more than 1, and the \"prefetchId\" will be defined on the `@prefetch` itself as an argument\n const prefetchID = prefetch ? \"__anonymous\" : undefined;\n\n const toolDirectives =\n directives?.filter((d) => d.name.value === \"tool\") ?? [];\n\n const tools = toolDirectives.map((directive) => {\n const nameArg = getDirectiveArgument(\"name\", directive);\n const descriptionArg = getDirectiveArgument(\"description\", directive);\n\n let name: string;\n if (nameArg) {\n name = getArgumentValue(nameArg, Kind.STRING);\n } else {\n invariant(\n toolDirectives.length === 1,\n `Operations with multiple @tool directives must provide a 'name' argument on each @tool`\n );\n invariant(\n definition.name?.value,\n `Anonymous operations cannot use @tool without providing a 'name' argument`\n );\n name = definition.name.value;\n }\n\n let description: string;\n if (descriptionArg) {\n description = getArgumentValue(descriptionArg, Kind.STRING);\n } else {\n invariant(\n toolDirectives.length === 1,\n `Operations with multiple @tool directives must provide a 'description' argument on each @tool`\n );\n invariant(\n definition.description?.value,\n `Operations using @tool without a 'description' argument must have a description on the operation definition`\n );\n description = definition.description.value;\n }\n\n const result = ToolDirectiveSchema.safeParse({\n name,\n description,\n extraInputs: maybeGetArgumentValue(\n getDirectiveArgument(\"extraInputs\", directive),\n Kind.LIST\n ),\n labels: maybeGetArgumentValue(\n getDirectiveArgument(\"labels\", directive),\n Kind.OBJECT\n ),\n });\n\n if (result.error) {\n throw z.prettifyError(result.error);\n }\n\n return result.data;\n });\n\n // TODO: Make this object satisfy the `ManifestOperation` type. Currently\n // it errors because we need more validation on a few of these fields\n return of({\n data: { id, name, type, body, variables, prefetch, prefetchID, tools },\n });\n});\n\nfunction removeManifestDirectives(doc: DocumentNode) {\n return removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n doc\n )!;\n}\n\n// Sort the definitions in this document so that operations come before fragments,\n// and so that each kind of definition is sorted by name.\nexport function sortTopLevelDefinitions(query: DocumentNode): DocumentNode {\n const definitions = [...query.definitions];\n // We want to avoid unnecessary dependencies, so write out a comparison\n // function instead of using _.orderBy.\n definitions.sort((a, b) => {\n // This is a reverse sort by kind, so that OperationDefinition precedes FragmentDefinition.\n if (a.kind > b.kind) {\n return -1;\n }\n if (a.kind < b.kind) {\n return 1;\n }\n\n // Extract the name from each definition. Jump through some hoops because\n // non-executable definitions don't have to have names (even though any\n // DocumentNode actually passed here should only have executable\n // definitions).\n const aName =\n a.kind === \"OperationDefinition\" || a.kind === \"FragmentDefinition\" ?\n (a.name?.value ?? \"\")\n : \"\";\n const bName =\n b.kind === \"OperationDefinition\" || b.kind === \"FragmentDefinition\" ?\n (b.name?.value ?? \"\")\n : \"\";\n\n // Sort by name ascending.\n if (aName < bName) {\n return -1;\n }\n if (aName > bName) {\n return 1;\n }\n\n // Assuming that the document is \"valid\", no operation or fragment name can appear\n // more than once, so we don't need to differentiate further to have a deterministic\n // sort.\n return 0;\n });\n return {\n ...query,\n definitions,\n };\n}\n\nfunction isNonEmptyObject<T extends object>(\n obj: T | null | undefined\n): obj is T {\n return !!obj && Object.keys(obj).length > 0;\n}\n\nasync function getAppsConfig() {\n const result = await explorer.search();\n const config = (result?.config ??\n {}) as Partial<ApolloClientAiAppsConfig.Config>;\n\n const parsed = ApolloClientAiAppsConfigSchema.safeParse(config);\n\n if (parsed.error) {\n throw z.prettifyError(parsed.error);\n }\n\n return parsed.data;\n}\n\nfunction getResourceFromConfig(\n appsConfig: z.infer<typeof ApolloClientAiAppsConfigSchema>,\n mode: string,\n target: apolloClientAiApps.Target\n) {\n if (!appsConfig.entry || !appsConfig.entry[mode]) {\n return;\n }\n\n const config = appsConfig.entry[mode];\n\n return typeof config === \"string\" ? config : config[target];\n}\n\nfunction readPackageJson(): Record<string, any> {\n if (readPackageJson.cache) {\n return readPackageJson.cache;\n }\n\n return (readPackageJson.cache = JSON.parse(\n fs.readFileSync(\"package.json\", \"utf-8\")\n ));\n}\n\nreadPackageJson.cache = undefined as Record<string, any> | undefined;\nreadPackageJson.resetCache = () => {\n readPackageJson.cache = undefined;\n};\n\nfunction writeFileSync(\n filepath: string,\n content: string,\n options: { cache?: boolean } = {}\n) {\n function writeFile() {\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n fs.writeFileSync(filepath, content, \"utf-8\");\n }\n\n if (!options.cache) {\n return writeFile();\n }\n\n const hash = md5(content);\n const cachedHash = writeFileSync.cache.get(filepath);\n\n if (hash !== cachedHash || !fs.existsSync(filepath)) {\n writeFileSync.cache.set(filepath, hash);\n writeFile();\n }\n}\n\nwriteFileSync.cache = new Map<string, string>();\n\nconst ToolDirectiveSchema = z.strictObject({\n name: z.stringFormat(\"toolName\", (value) => value.indexOf(\" \") === -1, {\n error: (iss) => `Tool with name \"${iss.input}\" must not contain spaces`,\n }),\n description: z.string(),\n extraInputs: z.optional(\n z.array(\n z.strictObject({\n name: z.string(),\n description: z.string(),\n type: z.literal([\"string\", \"boolean\", \"number\"]),\n })\n )\n ),\n labels: ApolloClientAiAppsConfigSchema.shape.labels.optional(),\n});\n"]}
1
+ {"version":3,"file":"apolloClientAiApps.js","sourceRoot":"","sources":["../../src/vite/apolloClientAiApps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,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CAAC,MAAM,CAAC,QAAQ,EAAE;CAC/D,CAAC,CAAC","sourcesContent":["import {\n defaultClientConditions,\n type Plugin,\n type ResolvedConfig,\n} from \"vite\";\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport * as recast from \"recast\";\nimport typescriptParser from \"recast/parsers/typescript.js\";\nimport { ApolloClient, ApolloLink, type DocumentNode } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client\";\nimport { equal } from \"@wry/equality\";\nimport { gqlPluckFromCodeStringSync } from \"@graphql-tools/graphql-tag-pluck\";\nimport { glob } from \"glob\";\nimport { print } from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { of } from \"rxjs\";\nimport { Kind, OperationTypeNode, parse, visit } from \"graphql\";\nimport {\n getArgumentValue,\n getDirectiveArgument,\n getTypeName,\n maybeGetArgumentValue,\n} from \"./utilities/graphql.js\";\nimport type {\n ApplicationManifest,\n ManifestOperation,\n} from \"../types/application-manifest\";\nimport { invariant } from \"../utilities/invariant.js\";\nimport { explorer } from \"./utilities/config.js\";\nimport type { ApolloClientAiAppsConfig } from \"../config/index.js\";\nimport { ApolloClientAiAppsConfigSchema } from \"../config/schema.js\";\nimport { z } from \"zod\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\nimport {\n buildImportStatement,\n buildPropertySignature,\n buildKeywordLiteral,\n printRecast,\n type TSInterfaceBody,\n} from \"./utilities/recast.js\";\nimport type { TypeScriptDocumentsPluginConfig } from \"@graphql-codegen/typescript-operations\";\n\nconst b = recast.types.builders;\n\nexport declare namespace apolloClientAiApps {\n export type Target = ApolloClientAiAppsConfig.AppTarget;\n\n export interface Options {\n targets: Target[];\n devTarget?: Target | undefined;\n appsOutDir: string;\n schema?: string | undefined;\n }\n}\n\nconst root = process.cwd();\n\nconst VALID_TARGETS: apolloClientAiApps.Target[] = [\"openai\", \"mcp\"];\n\nfunction isValidTarget(target: unknown): target is apolloClientAiApps.Target {\n return VALID_TARGETS.includes(target as apolloClientAiApps.Target);\n}\n\nfunction buildExtensions(target: apolloClientAiApps.Target) {\n return [\".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"].flatMap(\n (ext) => [`.${target}${ext}`, ext]\n );\n}\n\nexport function devTarget(target: string | undefined) {\n invariant(\n target === undefined || isValidTarget(target),\n `devTarget '${target}' is not a valid dev target. Must be one of ${VALID_TARGETS.join(\", \")}.`\n );\n\n return target;\n}\n\ninterface FileCache {\n hash: string;\n sources: DocumentNode[];\n}\n\nfunction md5(contents: string) {\n return createHash(\"md5\").update(contents).digest(\"hex\");\n}\n\n/**\n * Builds the AST for the comment used at the top of a generated file from this\n * plugin.\n *\n * @remarks\n * This comment informs users that generated files from this plugin should not\n * be edited since it is autogenerated by this plugin.\n */\nfunction buildHeaderComment() {\n return b.commentLine(\n \" This file is auto-generated by @apollo/client-ai-apps. Do not edit manually.\",\n true,\n false\n );\n}\n\n/**\n * Builds the `@apollo/client-ai-apps` ambient module declaration for the\n * `register.d.ts` file.\n *\n * @param registerInterfaceBody - The interface body for the `Register`\n * interface\n *\n * @example\n * ```ts\n * buildAmbientModuleDeclaration(interfaceBody);\n * // =>\n * // declare namespace \"@apollo/client-ai-apps\" {\n * // interface Register {\n * // // ...interfaceBody\n * // }\n * // }\n * ```\n */\nfunction buildAmbientModuleDeclaration(registerInterfaceBody: TSInterfaceBody) {\n const interfaceDeclaration = b.tsInterfaceDeclaration(\n b.identifier(\"Register\"),\n b.tsInterfaceBody(registerInterfaceBody)\n );\n\n const moduleDeclaration = b.tsModuleDeclaration(\n b.stringLiteral(\"@apollo/client-ai-apps\"),\n b.tsModuleBlock([interfaceDeclaration])\n );\n moduleDeclaration.declare = true;\n\n return moduleDeclaration;\n}\n\n/**\n * Gets the variables type name for an operation. GraphQL Codegen creates\n * variables types with the combination of operationName + operationType +\n * \"Variables\"\n *\n * @example\n * ```ts\n * getVariablesTypeName({ name: \"GetProduct\", type: \"query\" });\n * // => \"GetProductQueryVariables\"\n * ````\n */\nfunction getVariablesTypeName(operation: ManifestOperation) {\n const { name, type } = operation;\n\n return `${name}${type.charAt(0).toUpperCase()}${type.slice(1)}Variables`;\n}\n\n/**\n * Returns the code string written to the `.apollo-client-ai-apps/types/register.d.ts` files\n * for a given set of operations.\n */\nfunction getRegisteredTypeContents({\n operations,\n schema,\n flagSchemaBuildError = false,\n}: {\n operations: ManifestOperation[];\n schema: string | undefined;\n /**\n * Used during dev to avoid failing the build and instead output the error\n * to the console. When providing an error, the error message is generated as\n * a literal type value in the `register.d.ts` file so that users can see the\n * error message when hovering over the type.\n */\n flagSchemaBuildError?: false | Error;\n}) {\n if (flagSchemaBuildError) {\n const message = `[@apollo/client-ai-apps/vite]: There was an error building generated types. See the vite build output for more details.\\n\\n${flagSchemaBuildError.message}`;\n\n const importBaseStatement = buildImportStatement(\n [],\n \"@apollo/client-ai-apps\"\n );\n importBaseStatement.comments = [buildHeaderComment()];\n\n const typeAnnotation = b.tsLiteralType(b.stringLiteral(message));\n\n return printRecast(\n b.program([\n importBaseStatement,\n buildAmbientModuleDeclaration([\n buildPropertySignature(\"toolName\", typeAnnotation),\n buildPropertySignature(\n \"toolInputs\",\n b.tsTypeLiteral([buildPropertySignature(message, typeAnnotation)])\n ),\n ]),\n ])\n );\n }\n\n const toolNames = operations.flatMap((op) => op.tools.map((t) => t.name));\n\n if (toolNames.length === 0) {\n const emptyExport = b.exportNamedDeclaration(null);\n emptyExport.comments = [buildHeaderComment()];\n return printRecast(b.program([emptyExport]));\n }\n\n const importBaseStatement = buildImportStatement(\n [],\n \"@apollo/client-ai-apps\"\n );\n importBaseStatement.comments = [buildHeaderComment()];\n\n const toolNameProp = buildPropertySignature(\n \"toolName\",\n b.tsUnionType(toolNames.map((n) => b.tsLiteralType(b.stringLiteral(n))))\n );\n\n if (!schema) {\n return printRecast(\n b.program([\n importBaseStatement,\n buildAmbientModuleDeclaration([toolNameProp]),\n ])\n );\n }\n\n const importedVariableTypes = new Set<string>();\n const toolInputsValue: recast.types.namedTypes.TSPropertySignature[] = [];\n\n for (const operation of operations) {\n const variablesTypeName = getVariablesTypeName(operation);\n\n if (operation.tools.length) {\n importedVariableTypes.add(variablesTypeName);\n }\n\n for (const tool of operation.tools) {\n const variablesTypeRef = b.tsTypeReference(\n b.identifier(variablesTypeName)\n );\n let typeExpression:\n | recast.types.namedTypes.TSTypeReference\n | recast.types.namedTypes.TSIntersectionType = variablesTypeRef;\n\n if (tool.extraInputs?.length) {\n const extraInputsType = tool.extraInputs.map((ei) => {\n return buildPropertySignature(\n ei.name,\n buildKeywordLiteral(ei.type),\n true\n );\n });\n\n typeExpression = b.tsIntersectionType([\n variablesTypeRef,\n b.tsTypeLiteral(extraInputsType),\n ]);\n }\n\n toolInputsValue.push(buildPropertySignature(tool.name, typeExpression));\n }\n }\n\n return printRecast(\n b.program([\n importBaseStatement,\n buildImportStatement(\n Array.from(importedVariableTypes),\n \"./operation-types.js\",\n \"type\"\n ),\n buildAmbientModuleDeclaration([\n toolNameProp,\n buildPropertySignature(\"toolInputs\", b.tsTypeLiteral(toolInputsValue)),\n ]),\n ])\n );\n}\n\n/**\n * Generates and returns the code string written to the\n * `.apollo-client-ai-apps/types/operation-types.d.ts` file. Uses GraphQL\n * Codegen to introspect the given schema and extract variable types.\n */\nasync function generateOperationTypes(\n schema: string,\n documents: string[]\n): Promise<string> {\n const { generate } = await import(\"@graphql-codegen/cli\");\n\n if (documents.length === 0) {\n return `// Auto-generated by @apollo/client-ai-apps. Do not edit manually.\\nexport {};\\n`;\n }\n\n const output = await generate(\n {\n schema,\n documents,\n generates: {\n \"operation-types.d.ts\": {\n plugins: [\"typescript\", \"typescript-operations\"],\n config: {\n nonOptionalTypename: true,\n skipTypeNameForRoot: true,\n } satisfies TypeScriptDocumentsPluginConfig,\n },\n },\n silent: true,\n } as Parameters<typeof generate>[0],\n false\n );\n\n const content = (output as { filename: string; content: string }[])[0]\n .content;\n return `// Auto-generated by @apollo/client-ai-apps. Do not edit manually.\\n${content}`;\n}\n\n/**\n * Gets the name of an exported type (e.g. `export type x`) from a TypeScript\n * AST statement.\n */\nfunction getExportedTypeAliasName(\n statement: recast.types.namedTypes.Statement\n): string | undefined {\n if (statement.type !== \"ExportNamedDeclaration\") return;\n\n const declaration = (\n statement as recast.types.namedTypes.ExportNamedDeclaration\n ).declaration;\n\n if (!declaration || declaration.type !== \"TSTypeAliasDeclaration\") return;\n\n const alias = declaration as recast.types.namedTypes.TSTypeAliasDeclaration;\n return typeof alias.id.name === \"string\" ? alias.id.name : undefined;\n}\n\n/**\n * Removes all non-`*Variables` types from the `operation-types.d.ts` file.\n * The `typescript` and `typescript-operations` codegen plugins add full schema\n * types and operation types. This function ensures those unused types are\n * removed.\n */\nfunction filterOperationTypes(\n content: string,\n rootTypeNames: Set<string>\n): string {\n const ast = recast.parse(content, { parser: typescriptParser });\n const statements: recast.types.namedTypes.Statement[] = ast.program.body;\n const typeMap = new Map<\n string,\n recast.types.namedTypes.TSTypeAliasDeclaration\n >();\n\n for (const statement of statements) {\n const name = getExportedTypeAliasName(statement);\n\n if (name) {\n typeMap.set(\n name,\n (statement as recast.types.namedTypes.ExportNamedDeclaration)\n .declaration as recast.types.namedTypes.TSTypeAliasDeclaration\n );\n }\n }\n\n const reachable = new Set<string>(rootTypeNames);\n const queue = Array.from(rootTypeNames);\n\n while (queue.length > 0) {\n const name = queue.shift()!;\n const node = typeMap.get(name);\n\n if (!node) continue;\n\n recast.visit(node, {\n visitTSTypeReference(path) {\n const typeName = path.value.typeName?.name as string | undefined;\n\n if (typeName && !reachable.has(typeName)) {\n reachable.add(typeName);\n queue.push(typeName);\n }\n\n this.traverse(path);\n },\n });\n }\n\n ast.program.body = statements.filter((statement) => {\n const name = getExportedTypeAliasName(statement);\n return name === undefined || reachable.has(name);\n });\n\n return printRecast(ast);\n}\n\nexport function apolloClientAiApps(\n options: apolloClientAiApps.Options\n): Plugin {\n const targets = Array.from(new Set(options.targets));\n const {\n devTarget = targets.length === 1 ? targets[0] : undefined,\n appsOutDir,\n schema,\n } = options;\n let config!: ResolvedConfig;\n\n const fragments = createFragmentRegistry();\n\n invariant(\n Array.isArray(targets) && targets.length > 0,\n \"The `targets` option must be a non-empty array\"\n );\n\n invariant(\n targets.every(isValidTarget),\n `All targets must be one of: ${VALID_TARGETS.join(\", \")}`\n );\n\n invariant(\n path.basename(path.normalize(appsOutDir)) === \"apps\",\n \"`appsOutDir` must end with `apps` as the final path segment (e.g. `path/to/apps`).\"\n );\n\n const client = new ApolloClient({\n cache: new InMemoryCache({ fragments }),\n link: processQueryLink,\n });\n\n let sources: DocumentNode[] = [];\n\n function recomputeSources(cache: Map<string, FileCache>) {\n sources = Array.from(cache.values()).flatMap((entry) => entry.sources);\n }\n\n async function getManifestOperations() {\n if (sources === getManifestOperations.cache.sources) {\n return getManifestOperations.cache.manifestOperations;\n }\n\n const manifestOperations = [];\n for (const source of sources) {\n const operationDef = source.definitions.find(\n (d) => d.kind === Kind.OPERATION_DEFINITION\n );\n\n if (!operationDef) continue;\n\n switch (operationDef.operation) {\n case OperationTypeNode.QUERY: {\n const result = await client.query<ManifestOperation>({\n query: source,\n fetchPolicy: \"no-cache\",\n });\n\n manifestOperations.push(result.data!);\n break;\n }\n case OperationTypeNode.MUTATION: {\n const result = await client.mutate<ManifestOperation>({\n mutation: source,\n fetchPolicy: \"no-cache\",\n });\n\n manifestOperations.push(result.data!);\n break;\n }\n default:\n throw new Error(\n `Found unsupported operation type '${operationDef.operation}'. Only queries and mutations are supported.`\n );\n }\n }\n\n getManifestOperations.cache = { sources, manifestOperations };\n\n return manifestOperations;\n }\n\n getManifestOperations.cache = {\n sources,\n manifestOperations: [] as ManifestOperation[],\n };\n\n async function processFile(file: string) {\n const code = fs.readFileSync(file, \"utf-8\");\n\n if (!code.includes(\"gql\")) return;\n\n const fileHash = md5(code);\n if (processFile.cache.get(file)?.hash === fileHash) return;\n\n const sources = gqlPluckFromCodeStringSync(file, code, {\n modules: [\n { name: \"graphql-tag\", identifier: \"gql\" },\n { name: \"@apollo/client\", identifier: \"gql\" },\n ],\n }).map((source) => parse(source.body));\n\n const previousSources = processFile.cache.get(file)?.sources;\n\n if (previousSources && equal(sources, previousSources)) {\n processFile.cache.set(file, { hash: fileHash, sources: previousSources });\n return;\n }\n\n fragments.register(...sources);\n\n processFile.cache.set(file, { hash: fileHash, sources });\n recomputeSources(processFile.cache);\n }\n\n processFile.cache = new Map<string, FileCache>();\n\n async function generateManifest() {\n const appsConfig = await getAppsConfig();\n const operations = await getManifestOperations();\n\n invariant(\n operations.filter((o) => o.prefetch).length <= 1,\n \"Found multiple operations marked as `@prefetch`. You can only mark 1 operation with `@prefetch`.\"\n );\n\n function getBuildResourceForTarget(target: apolloClientAiApps.Target) {\n const entryPoint = getResourceFromConfig(appsConfig, config.mode, target);\n\n if (entryPoint) {\n return entryPoint;\n }\n\n if (config.mode === \"production\") {\n return `${target}/index.html`;\n }\n\n throw new Error(\n `No entry point found for mode \"${config.mode}\". Entry points other than \"development\" and \"production\" must be defined in package.json file.`\n );\n }\n\n let resource: ApplicationManifest[\"resource\"];\n if (config.command === \"serve\") {\n // Dev mode: resource is a string (dev server URL)\n resource =\n getResourceFromConfig(appsConfig, config.mode, devTarget!) ??\n `http${config.server.https ? \"s\" : \"\"}://${config.server.host ?? \"localhost\"}:${config.server.port}`;\n } else {\n resource = Object.fromEntries(\n targets.map((target) => [target, getBuildResourceForTarget(target)])\n ) as { mcp?: string; openai?: string };\n }\n\n const packageJson = readPackageJson();\n const appName = appsConfig.name ?? packageJson.name;\n\n invariant(\n appName,\n \"Error generating application manifest. Could not determine app name. Set `name` in your apollo-client-ai-apps config or `package.json`.\"\n );\n\n const manifest: ApplicationManifest = {\n format: \"apollo-ai-app-manifest\",\n version: \"1\",\n appVersion: appsConfig.version ?? packageJson.version,\n name: appsConfig.name ?? packageJson.name,\n description: appsConfig.description ?? packageJson.description,\n hash: createHash(\"sha256\").update(Date.now().toString()).digest(\"hex\"),\n operations,\n resource,\n csp: {\n baseUriDomains: appsConfig.csp?.baseUriDomains ?? [],\n connectDomains: appsConfig.csp?.connectDomains ?? [],\n frameDomains: appsConfig.csp?.frameDomains ?? [],\n redirectDomains: appsConfig.csp?.redirectDomains ?? [],\n resourceDomains: appsConfig.csp?.resourceDomains ?? [],\n },\n };\n\n if (isNonEmptyObject(appsConfig.widgetSettings)) {\n manifest.widgetSettings = appsConfig.widgetSettings;\n }\n\n if (isNonEmptyObject(appsConfig.labels)) {\n manifest.labels = appsConfig.labels;\n }\n\n const manifestContents = JSON.stringify(manifest);\n\n // Always write to build directory so the MCP server picks it up\n writeFileSync(\n path.resolve(root, appsOutDir, appName, \".application-manifest.json\"),\n manifestContents\n );\n\n // Always write to the dev location so that the app can bundle the manifest content\n writeFileSync(\".application-manifest.json\", manifestContents);\n\n const manifestTypesFilepath = \".application-manifest.d.json.ts\";\n if (!fs.existsSync(manifestTypesFilepath)) {\n const manifestImport = b.importDeclaration(\n [b.importSpecifier(b.identifier(\"ApplicationManifest\"))],\n b.stringLiteral(\"@apollo/client-ai-apps\"),\n \"type\"\n );\n const manifestId = b.identifier(\"manifest\");\n manifestId.typeAnnotation = b.tsTypeAnnotation(\n b.tsTypeReference(b.identifier(\"ApplicationManifest\"), null)\n );\n const manifestDeclaration = b.variableDeclaration(\"const\", [\n b.variableDeclarator(manifestId, null),\n ]) as recast.types.namedTypes.VariableDeclaration & { declare: boolean };\n manifestDeclaration.declare = true;\n\n const exportDefault = b.exportDefaultDeclaration(\n b.identifier(\"manifest\")\n );\n\n const content = printRecast(\n b.program([manifestImport, manifestDeclaration, exportDefault])\n );\n\n writeFileSync(manifestTypesFilepath, content);\n }\n }\n\n async function generateTypesFiles() {\n let flagSchemaBuildError: false | Error = false;\n const operations = await getManifestOperations();\n\n if (operations === generateTypesFiles.cache) {\n return;\n }\n\n generateTypesFiles.cache = operations;\n\n if (schema) {\n try {\n const opTypesContent = await generateOperationTypes(\n schema,\n operations.map((op) => op.body)\n );\n\n const rootTypeNames = new Set(\n operations.flatMap((op) =>\n op.tools.length > 0 ? [getVariablesTypeName(op)] : []\n )\n );\n\n writeFileSync(\n path.resolve(\n root,\n \".apollo-client-ai-apps/types/operation-types.d.ts\"\n ),\n filterOperationTypes(opTypesContent, rootTypeNames),\n { cache: true }\n );\n } catch (e) {\n if (config.command === \"build\") {\n throw e;\n }\n\n flagSchemaBuildError = e as Error;\n console.error(\"[@apollo/client-ai-apps/vite]:\", e);\n }\n }\n\n const typesFileContents = getRegisteredTypeContents({\n operations,\n schema,\n flagSchemaBuildError,\n });\n\n writeFileSync(\n path.resolve(root, \".apollo-client-ai-apps/types/register.d.ts\"),\n typesFileContents,\n { cache: true }\n );\n }\n\n generateTypesFiles.cache = [] as ManifestOperation[] | undefined;\n\n return {\n name: \"@apollo/client-ai-apps/vite\",\n async buildStart() {\n // Scan all files on startup\n const files = await glob(\"./src/**/*.{ts,tsx,js,jsx}\", { fs });\n\n for (const file of files) {\n const fullPath = path.resolve(root, file);\n await processFile(fullPath);\n }\n\n // We don't want to do this here on builds cause it just gets overwritten anyways. We'll call it on writeBundle instead.\n if (config.command === \"serve\") {\n await Promise.all([generateManifest(), generateTypesFiles()]);\n }\n },\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n async configEnvironment(name) {\n if (!targets.includes(name as any)) return;\n\n const appsConfig = await getAppsConfig();\n const appName = appsConfig.name ?? readPackageJson().name;\n\n invariant(\n appName,\n \"Could not determine app name. Set `name` in your apollo-client-ai-apps config or `package.json`.\"\n );\n\n return {\n build: {\n outDir: path.join(appsOutDir, appName, name),\n },\n };\n },\n configureServer(server) {\n server.watcher.on(\"change\", async (file) => {\n if (file.endsWith(\"package.json\")) {\n readPackageJson.resetCache();\n await generateManifest();\n } else if (file.match(/\\.?apollo-client-ai-apps\\.config\\.\\w+$/)) {\n explorer.clearCaches();\n await generateManifest();\n } else if (file.match(/\\.(jsx?|tsx?)$/)) {\n await processFile(file);\n await Promise.all([generateManifest(), generateTypesFiles()]);\n }\n });\n },\n\n config(userConfig, { command }) {\n if (userConfig.build?.outDir) {\n console.warn(\n \"[@apollo/client-ai-apps/vite] `build.outDir` is set in your Vite config but will be \" +\n \"ignored. Use `appsOutDir` in the plugin options to control the output location.\"\n );\n }\n\n if (command === \"serve\") {\n invariant(\n isValidTarget(devTarget) || targets.length === 1,\n \"`devTarget` must be set for development when using multiple targets.\"\n );\n\n const target = devTarget ?? targets[0];\n\n return {\n resolve: {\n extensions: buildExtensions(target),\n conditions: [target, ...defaultClientConditions],\n },\n };\n }\n\n return {\n environments: Object.fromEntries(\n targets.map((target) => [\n target,\n {\n consumer: \"client\",\n webCompatible: true,\n resolve: {\n extensions: buildExtensions(target),\n conditions: [target, ...defaultClientConditions],\n },\n },\n ])\n ),\n builder: {\n buildApp: async (builder) => {\n await Promise.all(\n targets.map((target) =>\n builder.build(builder.environments[target])\n )\n );\n },\n },\n };\n },\n transformIndexHtml(html, ctx) {\n if (!ctx.server) return html;\n\n let baseUrl = (\n ctx.server.config?.server?.origin ??\n ctx.server.resolvedUrls?.local[0] ??\n \"\"\n ).replace(/\\/$/, \"\");\n baseUrl = baseUrl.replace(/\\/$/, \"\");\n\n return (\n html\n // import \"/@vite/...\" or \"/@react-refresh\"\n .replace(/(from\\s+[\"'])\\/([^\"']+)/g, `$1${baseUrl}/$2`)\n // src=\"/src/...\"\n .replace(/(src=[\"'])\\/([^\"']+)/gi, `$1${baseUrl}/$2`)\n );\n },\n async writeBundle() {\n await Promise.all([generateManifest(), generateTypesFiles()]);\n },\n } satisfies Plugin;\n}\n\nconst processQueryLink = new ApolloLink((operation) => {\n const body = print(\n removeOperationDescription(\n removeManifestDirectives(sortTopLevelDefinitions(operation.query))\n )\n );\n const name = operation.operationName;\n const definition = operation.query.definitions.find(\n (d) => d.kind === \"OperationDefinition\"\n );\n\n // Use `operation.query` so that the error reflects the end-user defined\n // document, not our sorted one\n invariant(\n definition,\n `Document does not contain an operation:\\n${print(operation.query)}`\n );\n\n const { directives, operation: type } = definition;\n\n const variables = definition.variableDefinitions?.reduce(\n (obj, varDef) => ({\n ...obj,\n [varDef.variable.name.value]: getTypeName(varDef.type),\n }),\n {}\n );\n\n const prefetch = directives?.some((d) => d.name.value === \"prefetch\");\n const id = createHash(\"sha256\").update(body).digest(\"hex\");\n // TODO: For now, you can only have 1 operation marked as prefetch. In the future, we'll likely support more than 1, and the \"prefetchId\" will be defined on the `@prefetch` itself as an argument\n const prefetchID = prefetch ? \"__anonymous\" : undefined;\n\n const toolDirectives =\n directives?.filter((d) => d.name.value === \"tool\") ?? [];\n\n const tools = toolDirectives.map((directive) => {\n const nameArg = getDirectiveArgument(\"name\", directive);\n const descriptionArg = getDirectiveArgument(\"description\", directive);\n\n let name: string;\n if (nameArg) {\n name = getArgumentValue(nameArg, Kind.STRING);\n } else {\n invariant(\n toolDirectives.length === 1,\n `Operations with multiple @tool directives must provide a 'name' argument on each @tool`\n );\n invariant(\n definition.name?.value,\n `Anonymous operations cannot use @tool without providing a 'name' argument`\n );\n name = definition.name.value;\n }\n\n let description: string;\n if (descriptionArg) {\n description = getArgumentValue(descriptionArg, Kind.STRING);\n } else {\n invariant(\n toolDirectives.length === 1,\n `Operations with multiple @tool directives must provide a 'description' argument on each @tool`\n );\n invariant(\n definition.description?.value,\n `Operations using @tool without a 'description' argument must have a description on the operation definition`\n );\n description = definition.description.value;\n }\n\n const result = ToolDirectiveSchema.safeParse({\n name,\n description,\n extraInputs: maybeGetArgumentValue(\n getDirectiveArgument(\"extraInputs\", directive),\n Kind.LIST\n ),\n labels: maybeGetArgumentValue(\n getDirectiveArgument(\"labels\", directive),\n Kind.OBJECT\n ),\n });\n\n if (result.error) {\n throw z.prettifyError(result.error);\n }\n\n return result.data;\n });\n\n // TODO: Make this object satisfy the `ManifestOperation` type. Currently\n // it errors because we need more validation on a few of these fields\n return of({\n data: { id, name, type, body, variables, prefetch, prefetchID, tools },\n });\n});\n\nfunction removeOperationDescription(doc: DocumentNode): DocumentNode {\n return visit(doc, {\n OperationDefinition(node) {\n return { ...node, description: undefined };\n },\n });\n}\n\nfunction removeManifestDirectives(doc: DocumentNode) {\n return removeDirectivesFromDocument(\n [{ name: \"prefetch\" }, { name: \"tool\" }],\n doc\n )!;\n}\n\n// Sort the definitions in this document so that operations come before fragments,\n// and so that each kind of definition is sorted by name.\nexport function sortTopLevelDefinitions(query: DocumentNode): DocumentNode {\n const definitions = [...query.definitions];\n // We want to avoid unnecessary dependencies, so write out a comparison\n // function instead of using _.orderBy.\n definitions.sort((a, b) => {\n // This is a reverse sort by kind, so that OperationDefinition precedes FragmentDefinition.\n if (a.kind > b.kind) {\n return -1;\n }\n if (a.kind < b.kind) {\n return 1;\n }\n\n // Extract the name from each definition. Jump through some hoops because\n // non-executable definitions don't have to have names (even though any\n // DocumentNode actually passed here should only have executable\n // definitions).\n const aName =\n a.kind === \"OperationDefinition\" || a.kind === \"FragmentDefinition\" ?\n (a.name?.value ?? \"\")\n : \"\";\n const bName =\n b.kind === \"OperationDefinition\" || b.kind === \"FragmentDefinition\" ?\n (b.name?.value ?? \"\")\n : \"\";\n\n // Sort by name ascending.\n if (aName < bName) {\n return -1;\n }\n if (aName > bName) {\n return 1;\n }\n\n // Assuming that the document is \"valid\", no operation or fragment name can appear\n // more than once, so we don't need to differentiate further to have a deterministic\n // sort.\n return 0;\n });\n return {\n ...query,\n definitions,\n };\n}\n\nfunction isNonEmptyObject<T extends object>(\n obj: T | null | undefined\n): obj is T {\n return !!obj && Object.keys(obj).length > 0;\n}\n\nasync function getAppsConfig() {\n const result = await explorer.search();\n const config = (result?.config ??\n {}) as Partial<ApolloClientAiAppsConfig.Config>;\n\n const parsed = ApolloClientAiAppsConfigSchema.safeParse(config);\n\n if (parsed.error) {\n throw z.prettifyError(parsed.error);\n }\n\n return parsed.data;\n}\n\nfunction getResourceFromConfig(\n appsConfig: z.infer<typeof ApolloClientAiAppsConfigSchema>,\n mode: string,\n target: apolloClientAiApps.Target\n) {\n if (!appsConfig.entry || !appsConfig.entry[mode]) {\n return;\n }\n\n const config = appsConfig.entry[mode];\n\n return typeof config === \"string\" ? config : config[target];\n}\n\nfunction readPackageJson(): Record<string, any> {\n if (readPackageJson.cache) {\n return readPackageJson.cache;\n }\n\n return (readPackageJson.cache = JSON.parse(\n fs.readFileSync(\"package.json\", \"utf-8\")\n ));\n}\n\nreadPackageJson.cache = undefined as Record<string, any> | undefined;\nreadPackageJson.resetCache = () => {\n readPackageJson.cache = undefined;\n};\n\nfunction writeFileSync(\n filepath: string,\n content: string,\n options: { cache?: boolean } = {}\n) {\n function writeFile() {\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n fs.writeFileSync(filepath, content, \"utf-8\");\n }\n\n if (!options.cache) {\n return writeFile();\n }\n\n const hash = md5(content);\n const cachedHash = writeFileSync.cache.get(filepath);\n\n if (hash !== cachedHash || !fs.existsSync(filepath)) {\n writeFileSync.cache.set(filepath, hash);\n writeFile();\n }\n}\n\nwriteFileSync.cache = new Map<string, string>();\n\nconst ToolDirectiveSchema = z.strictObject({\n name: z.stringFormat(\"toolName\", (value) => value.indexOf(\" \") === -1, {\n error: (iss) => `Tool with name \"${iss.input}\" must not contain spaces`,\n }),\n description: z.string(),\n extraInputs: z.optional(\n z.array(\n z.strictObject({\n name: z.string(),\n description: z.string(),\n type: z.literal([\"string\", \"boolean\", \"number\"]),\n })\n )\n ),\n labels: ApolloClientAiAppsConfigSchema.shape.labels.optional(),\n});\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://www.schemastore.org/package.json",
3
3
  "name": "@apollo/client-ai-apps",
4
- "version": "0.6.1",
4
+ "version": "0.6.3",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -9,7 +9,7 @@ import type {
9
9
  OperationVariables,
10
10
  } from "@apollo/client";
11
11
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
12
- import { parse } from "graphql";
12
+ import { parse, visit } from "graphql";
13
13
  import { equal } from "@wry/equality";
14
14
  import { __DEV__ } from "@apollo/client/utilities/environment";
15
15
  import type { ApplicationManifest } from "../../types/application-manifest.js";
@@ -52,10 +52,16 @@ export class ApolloClient extends BaseApolloClient {
52
52
  link,
53
53
  // Strip out the prefetch/tool directives so they don't get sent with the operation to the server
54
54
  documentTransform: new DocumentTransform((document) => {
55
- return removeDirectivesFromDocument(
55
+ const serverDocument = removeDirectivesFromDocument(
56
56
  [{ name: "prefetch" }, { name: "tool" }],
57
57
  document
58
58
  )!;
59
+
60
+ return visit(serverDocument, {
61
+ OperationDefinition(node) {
62
+ return { ...node, description: undefined };
63
+ },
64
+ });
59
65
  }).concat(options.documentTransform ?? DocumentTransform.identity()),
60
66
  });
61
67
 
@@ -7,7 +7,7 @@ import type {
7
7
  OperationVariables,
8
8
  } from "@apollo/client";
9
9
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
10
- import { parse } from "graphql";
10
+ import { parse, visit } from "graphql";
11
11
  import { equal } from "@wry/equality";
12
12
  import { __DEV__ } from "@apollo/client/utilities/environment";
13
13
  import type { ApplicationManifest } from "../../types/application-manifest.js";
@@ -50,10 +50,16 @@ export class ApolloClient extends BaseApolloClient {
50
50
  link,
51
51
  // Strip out the prefetch/tool directives so they don't get sent with the operation to the server
52
52
  documentTransform: new DocumentTransform((document) => {
53
- return removeDirectivesFromDocument(
53
+ const serverDocument = removeDirectivesFromDocument(
54
54
  [{ name: "prefetch" }, { name: "tool" }],
55
55
  document
56
56
  )!;
57
+
58
+ return visit(serverDocument, {
59
+ OperationDefinition(node) {
60
+ return { ...node, description: undefined };
61
+ },
62
+ });
57
63
  }).concat(options.documentTransform ?? DocumentTransform.identity()),
58
64
  });
59
65
 
@@ -67,6 +67,17 @@ export class McpAppManager {
67
67
 
68
68
  await this.connectToHost();
69
69
 
70
+ // After a page refresh, OpenAI does not re-send `ui/notifications/tool-result`.
71
+ // Instead, the tool result is available immediately via `window.openai.toolOutput`.
72
+ // If it's already set, resolve the promise now rather than waiting for the
73
+ // notification that will never arrive.
74
+ if (window.openai.toolOutput !== null) {
75
+ toolResult.resolve({
76
+ structuredContent: window.openai.toolOutput,
77
+ content: [],
78
+ });
79
+ }
80
+
70
81
  const { structuredContent } = await toolResult.promise;
71
82
 
72
83
  this.#toolName = this.app.getHostContext()?.toolInfo?.tool.name;
@@ -400,6 +400,66 @@ describe("prefetchData", () => {
400
400
  });
401
401
  });
402
402
 
403
+ test("connects using window.openai.toolOutput when tool-result notification is not sent", async () => {
404
+ stubOpenAiGlobals({
405
+ toolOutput: {
406
+ result: {
407
+ data: {
408
+ product: {
409
+ id: "1",
410
+ title: "Pen",
411
+ rating: 5,
412
+ price: 1.0,
413
+ description: "Awesome pen",
414
+ images: [],
415
+ __typename: "Product",
416
+ },
417
+ },
418
+ },
419
+ },
420
+ toolInput: { id: "1" },
421
+ });
422
+ using _ = spyOnConsole("debug");
423
+ const client = new ApolloClient({
424
+ cache: new InMemoryCache(),
425
+ manifest: mockApplicationManifest(),
426
+ });
427
+ using host = await mockMcpHost({
428
+ hostContext: minimalHostContextWithToolName("GetProduct"),
429
+ });
430
+ host.onCleanup(() => client.stop());
431
+
432
+ host.sendToolInput({ arguments: { id: "1" } });
433
+ // No host.sendToolResult() — simulates page reload where ChatGPT does not
434
+ // re-send the tool-result notification
435
+
436
+ await client.connect();
437
+
438
+ // Flush pending setImmediate callbacks (e.g. ResizeObserver in happy-dom)
439
+ // before `using host` disposes and closes the app connection.
440
+ await new Promise((resolve) => setImmediate(resolve));
441
+
442
+ expect(client.extract()).toMatchInlineSnapshot(`
443
+ {
444
+ "Product:1": {
445
+ "__typename": "Product",
446
+ "description": "Awesome pen",
447
+ "id": "1",
448
+ "images": [],
449
+ "price": 1,
450
+ "rating": 5,
451
+ "title": "Pen",
452
+ },
453
+ "ROOT_QUERY": {
454
+ "__typename": "Query",
455
+ "product({"id":"1"})": {
456
+ "__ref": "Product:1",
457
+ },
458
+ },
459
+ }
460
+ `);
461
+ });
462
+
403
463
  describe("custom links", () => {
404
464
  test("allows for custom links provided to the constructor", async () => {
405
465
  stubOpenAiGlobals();
@@ -777,6 +777,11 @@ describe("@tool validation", () => {
777
777
  },
778
778
  ]
779
779
  `);
780
+ expect(manifest.operations[0].body).toMatchInlineSnapshot(`
781
+ "query HelloWorldQuery {
782
+ helloWorld
783
+ }"
784
+ `);
780
785
  });
781
786
 
782
787
  test("uses operation name and description when both are omitted from @tool", async () => {
@@ -808,6 +813,11 @@ describe("@tool validation", () => {
808
813
  },
809
814
  ]
810
815
  `);
816
+ expect(manifest.operations[0].body).toMatchInlineSnapshot(`
817
+ "query HelloWorldQuery {
818
+ helloWorld
819
+ }"
820
+ `);
811
821
  });
812
822
 
813
823
  test("errors when tool name contains spaces", async () => {
@@ -16,7 +16,7 @@ import { glob } from "glob";
16
16
  import { print } from "@apollo/client/utilities";
17
17
  import { removeDirectivesFromDocument } from "@apollo/client/utilities/internal";
18
18
  import { of } from "rxjs";
19
- import { Kind, OperationTypeNode, parse } from "graphql";
19
+ import { Kind, OperationTypeNode, parse, visit } from "graphql";
20
20
  import {
21
21
  getArgumentValue,
22
22
  getDirectiveArgument,
@@ -805,7 +805,9 @@ export function apolloClientAiApps(
805
805
 
806
806
  const processQueryLink = new ApolloLink((operation) => {
807
807
  const body = print(
808
- removeManifestDirectives(sortTopLevelDefinitions(operation.query))
808
+ removeOperationDescription(
809
+ removeManifestDirectives(sortTopLevelDefinitions(operation.query))
810
+ )
809
811
  );
810
812
  const name = operation.operationName;
811
813
  const definition = operation.query.definitions.find(
@@ -898,6 +900,14 @@ const processQueryLink = new ApolloLink((operation) => {
898
900
  });
899
901
  });
900
902
 
903
+ function removeOperationDescription(doc: DocumentNode): DocumentNode {
904
+ return visit(doc, {
905
+ OperationDefinition(node) {
906
+ return { ...node, description: undefined };
907
+ },
908
+ });
909
+ }
910
+
901
911
  function removeManifestDirectives(doc: DocumentNode) {
902
912
  return removeDirectivesFromDocument(
903
913
  [{ name: "prefetch" }, { name: "tool" }],