@apollo/client-ai-apps 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/dist/core/typeRegistration.d.ts +33 -0
  3. package/dist/core/typeRegistration.d.ts.map +1 -0
  4. package/dist/core/typeRegistration.js +2 -0
  5. package/dist/core/typeRegistration.js.map +1 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/mcp/react/hooks/useToolInfo.d.ts +3 -0
  10. package/dist/mcp/react/hooks/useToolInfo.d.ts.map +1 -0
  11. package/dist/mcp/react/hooks/useToolInfo.js +10 -0
  12. package/dist/mcp/react/hooks/useToolInfo.js.map +1 -0
  13. package/dist/mcp/react/hooks/useToolInput.d.ts +6 -1
  14. package/dist/mcp/react/hooks/useToolInput.d.ts.map +1 -1
  15. package/dist/mcp/react/hooks/useToolInput.js +4 -0
  16. package/dist/mcp/react/hooks/useToolInput.js.map +1 -1
  17. package/dist/mcp/react/hooks/useToolName.d.ts +6 -1
  18. package/dist/mcp/react/hooks/useToolName.d.ts.map +1 -1
  19. package/dist/mcp/react/hooks/useToolName.js +4 -0
  20. package/dist/mcp/react/hooks/useToolName.js.map +1 -1
  21. package/dist/mcp/react/index.d.ts +1 -0
  22. package/dist/mcp/react/index.d.ts.map +1 -1
  23. package/dist/mcp/react/index.js +1 -0
  24. package/dist/mcp/react/index.js.map +1 -1
  25. package/dist/openai/react/hooks/useToolInfo.d.ts +3 -0
  26. package/dist/openai/react/hooks/useToolInfo.d.ts.map +1 -0
  27. package/dist/openai/react/hooks/useToolInfo.js +10 -0
  28. package/dist/openai/react/hooks/useToolInfo.js.map +1 -0
  29. package/dist/openai/react/hooks/useToolInput.d.ts +6 -1
  30. package/dist/openai/react/hooks/useToolInput.d.ts.map +1 -1
  31. package/dist/openai/react/hooks/useToolInput.js +4 -0
  32. package/dist/openai/react/hooks/useToolInput.js.map +1 -1
  33. package/dist/openai/react/hooks/useToolName.d.ts +6 -1
  34. package/dist/openai/react/hooks/useToolName.d.ts.map +1 -1
  35. package/dist/openai/react/hooks/useToolName.js +4 -0
  36. package/dist/openai/react/hooks/useToolName.js.map +1 -1
  37. package/dist/openai/react/index.d.ts +1 -0
  38. package/dist/openai/react/index.d.ts.map +1 -1
  39. package/dist/openai/react/index.js +1 -0
  40. package/dist/openai/react/index.js.map +1 -1
  41. package/dist/react/index.d.ts +9 -0
  42. package/dist/react/index.d.ts.map +1 -1
  43. package/dist/react/index.js +9 -0
  44. package/dist/react/index.js.map +1 -1
  45. package/dist/react/index.mcp.d.ts +1 -1
  46. package/dist/react/index.mcp.d.ts.map +1 -1
  47. package/dist/react/index.mcp.js +1 -1
  48. package/dist/react/index.mcp.js.map +1 -1
  49. package/dist/react/index.openai.d.ts +1 -1
  50. package/dist/react/index.openai.d.ts.map +1 -1
  51. package/dist/react/index.openai.js +1 -1
  52. package/dist/react/index.openai.js.map +1 -1
  53. package/dist/tsconfig/core/tsconfig.json +2 -0
  54. package/dist/tsconfig/mcp/tsconfig.json +2 -0
  55. package/dist/tsconfig/openai/tsconfig.json +2 -0
  56. package/dist/vite/apolloClientAiApps.d.ts +1 -0
  57. package/dist/vite/apolloClientAiApps.d.ts.map +1 -1
  58. package/dist/vite/apolloClientAiApps.js +337 -41
  59. package/dist/vite/apolloClientAiApps.js.map +1 -1
  60. package/dist/vite/utilities/recast.d.ts +54 -0
  61. package/dist/vite/utilities/recast.d.ts.map +1 -0
  62. package/dist/vite/utilities/recast.js +71 -0
  63. package/dist/vite/utilities/recast.js.map +1 -0
  64. package/package.json +7 -3
  65. package/src/core/typeRegistration.ts +32 -0
  66. package/src/index.ts +7 -0
  67. package/src/mcp/react/hooks/__tests__/useToolInfo.test.tsx +53 -0
  68. package/src/mcp/react/hooks/useToolInfo.ts +13 -0
  69. package/src/mcp/react/hooks/useToolInput.ts +6 -1
  70. package/src/mcp/react/hooks/useToolName.ts +6 -1
  71. package/src/mcp/react/index.ts +1 -0
  72. package/src/openai/react/hooks/__tests__/useToolInfo.test.tsx +92 -0
  73. package/src/openai/react/hooks/useToolInfo.ts +13 -0
  74. package/src/openai/react/hooks/useToolInput.ts +6 -1
  75. package/src/openai/react/hooks/useToolName.ts +6 -1
  76. package/src/openai/react/index.ts +1 -0
  77. package/src/react/index.mcp.ts +1 -0
  78. package/src/react/index.openai.ts +1 -0
  79. package/src/react/index.ts +11 -0
  80. package/src/tsconfig/core/tsconfig.json +2 -0
  81. package/src/tsconfig/mcp/tsconfig.json +2 -0
  82. package/src/tsconfig/openai/tsconfig.json +2 -0
  83. package/src/vite/__tests__/apolloClientAiApps.test.ts +744 -6
  84. package/src/vite/apolloClientAiApps.ts +552 -66
  85. package/src/vite/utilities/recast.ts +100 -0
@@ -1 +1 @@
1
- {"version":3,"file":"apolloClientAiApps.js","sourceRoot":"","sources":["../../src/vite/apolloClientAiApps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,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,EAAE,YAAY,EAAE,UAAU,EAAqB,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,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,IAAI,EAAE,iBAAiB,EAAE,KAAK,E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8BAA8B,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE;CAC/D,CAAC,CAAC","sourcesContent":["import {\n defaultClientConditions,\n type Environment,\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 { ApolloClient, ApolloLink, type DocumentNode } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client\";\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\";\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 }\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 file: string;\n hash: string;\n sources: DocumentNode[];\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 } = options;\n const cache = new Map<string, FileCache>();\n\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 async function processFile(file: string) {\n const code = fs.readFileSync(file, \"utf-8\");\n\n if (!code.includes(\"gql\")) return;\n\n const fileHash = createHash(\"md5\").update(code).digest(\"hex\");\n if (cache.get(file)?.hash === fileHash) return;\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 fragments.register(...sources);\n\n cache.set(file, {\n file: file,\n hash: fileHash,\n sources,\n });\n }\n\n async function generateManifest(environment?: Environment) {\n const appsConfig = await getAppsConfig();\n const sources = Array.from(cache.values()).flatMap(\n (entry) => entry.sources\n );\n\n const operations: ManifestOperation[] = [];\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 operations.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 operations.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 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 outDir = path.join(appsOutDir, appName);\n\n // Always write to build directory so the MCP server picks it up\n const dest = path.resolve(root, outDir, \".application-manifest.json\");\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, JSON.stringify(manifest));\n\n // Always write to the dev location so that the app can bundle the manifest content\n fs.writeFileSync(\".application-manifest.json\", JSON.stringify(manifest));\n }\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 generateManifest(this.environment);\n }\n },\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n async configEnvironment(name, { build }) {\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 generateManifest();\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 generateManifest(this.environment);\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 tools = directives\n ?.filter((d) => d.name.value === \"tool\")\n .map((directive) => {\n const result = ToolDirectiveSchema.safeParse({\n name: getArgumentValue(\n getDirectiveArgument(\"name\", directive, { required: true }),\n Kind.STRING\n ),\n description: getArgumentValue(\n getDirectiveArgument(\"description\", directive, { required: true }),\n Kind.STRING\n ),\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\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
+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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"]}
@@ -0,0 +1,54 @@
1
+ import * as recast from "recast";
2
+ import type { ManifestExtraInput } from "../../types/application-manifest.js";
3
+ declare const b: import("ast-types/lib/gen/builders").builders;
4
+ export type TSInterfaceBody = Parameters<typeof b.tsInterfaceBody>[0];
5
+ /**
6
+ * Builds an import statement with named imports.
7
+ *
8
+ * @example
9
+ *
10
+ * ```ts
11
+ * buildImportStatement(
12
+ * ["a", "b"],
13
+ * "./path",
14
+ * );
15
+ * // => import { a, b } from "./path";
16
+ * ```
17
+ */
18
+ export declare function buildImportStatement(specifiers: string[], source: string, importKind?: "type" | "value"): recast.types.namedTypes.ImportDeclaration;
19
+ type TSTypeAnnotation = Parameters<typeof b.tsTypeAnnotation>[0];
20
+ /**
21
+ * Builds a key/value pair for use in a type. Automatically quotes the key if it
22
+ * contains invalid JavaScript identifier characters.
23
+ *
24
+ * @example
25
+ *
26
+ * ```ts
27
+ * buildPropertySignature(
28
+ * "key"
29
+ * b.tsLiteralType(b.tsStringKeyword())
30
+ * );
31
+ * // => key: string
32
+ * ```
33
+ */
34
+ export declare function buildPropertySignature(keyName: string, value: TSTypeAnnotation, optional?: boolean): recast.types.namedTypes.TSPropertySignature;
35
+ type SupportedLiteralTypes = ManifestExtraInput["type"];
36
+ /**
37
+ * Returns a TypeScript literal type from a string.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * buildKeywordLiteral("string");
42
+ * // => string
43
+ *
44
+ * buildKeywordLiteral("number");
45
+ * // => number
46
+ * ````
47
+ */
48
+ export declare function buildKeywordLiteral(type: SupportedLiteralTypes): recast.types.namedTypes.TSBooleanKeyword | recast.types.namedTypes.TSNumberKeyword | recast.types.namedTypes.TSStringKeyword;
49
+ /**
50
+ * Pretty prints the TypeScript AST into a code string.
51
+ */
52
+ export declare function printRecast(ast: recast.types.ASTNode): string;
53
+ export {};
54
+ //# sourceMappingURL=recast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recast.d.ts","sourceRoot":"","sources":["../../../src/vite/utilities/recast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AAE9E,QAAA,MAAM,CAAC,+CAAwB,CAAC;AAEhC,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;AAEtE;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,MAAM,EAAE,EACpB,MAAM,EAAE,MAAM,EACd,UAAU,GAAE,MAAM,GAAG,OAAiB,6CAOvC;AAED,KAAK,gBAAgB,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;AAGjE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,gBAAgB,EACvB,QAAQ,UAAQ,+CASjB;AAID,KAAK,qBAAqB,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,qBAAqB,gIAa9D;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,UAEpD"}
@@ -0,0 +1,71 @@
1
+ import * as recast from "recast";
2
+ const b = recast.types.builders;
3
+ /**
4
+ * Builds an import statement with named imports.
5
+ *
6
+ * @example
7
+ *
8
+ * ```ts
9
+ * buildImportStatement(
10
+ * ["a", "b"],
11
+ * "./path",
12
+ * );
13
+ * // => import { a, b } from "./path";
14
+ * ```
15
+ */
16
+ export function buildImportStatement(specifiers, source, importKind = "value") {
17
+ return b.importDeclaration(specifiers.map((s) => b.importSpecifier(b.identifier(s))), b.stringLiteral(source), importKind);
18
+ }
19
+ const VALID_IDENTIFIER = /^[$_a-zA-Z][a-zA-Z0-9_$]*$/;
20
+ /**
21
+ * Builds a key/value pair for use in a type. Automatically quotes the key if it
22
+ * contains invalid JavaScript identifier characters.
23
+ *
24
+ * @example
25
+ *
26
+ * ```ts
27
+ * buildPropertySignature(
28
+ * "key"
29
+ * b.tsLiteralType(b.tsStringKeyword())
30
+ * );
31
+ * // => key: string
32
+ * ```
33
+ */
34
+ export function buildPropertySignature(keyName, value, optional = false) {
35
+ return b.tsPropertySignature(VALID_IDENTIFIER.test(keyName) ?
36
+ b.identifier(keyName)
37
+ : b.stringLiteral(keyName), b.tsTypeAnnotation(value), optional);
38
+ }
39
+ /**
40
+ * Returns a TypeScript literal type from a string.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * buildKeywordLiteral("string");
45
+ * // => string
46
+ *
47
+ * buildKeywordLiteral("number");
48
+ * // => number
49
+ * ````
50
+ */
51
+ export function buildKeywordLiteral(type) {
52
+ switch (type) {
53
+ case "string":
54
+ return b.tsStringKeyword();
55
+ case "boolean":
56
+ return b.tsBooleanKeyword();
57
+ case "number":
58
+ return b.tsNumberKeyword();
59
+ default: {
60
+ const _ = type;
61
+ throw new Error(`Unexpected input type: ${_}`);
62
+ }
63
+ }
64
+ }
65
+ /**
66
+ * Pretty prints the TypeScript AST into a code string.
67
+ */
68
+ export function printRecast(ast) {
69
+ return recast.prettyPrint(ast, { tabWidth: 2, quote: "double" }).code;
70
+ }
71
+ //# sourceMappingURL=recast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recast.js","sourceRoot":"","sources":["../../../src/vite/utilities/recast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAGjC,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC;AAIhC;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,oBAAoB,CAClC,UAAoB,EACpB,MAAc,EACd,aAA+B,OAAO;IAEtC,OAAO,CAAC,CAAC,iBAAiB,CACxB,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EACzD,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,EACvB,UAAU,CACX,CAAC;AACJ,CAAC;AAGD,MAAM,gBAAgB,GAAG,4BAA4B,CAAC;AAEtD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAe,EACf,KAAuB,EACvB,QAAQ,GAAG,KAAK;IAEhB,OAAO,CAAC,CAAC,mBAAmB,CAC1B,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QAC9B,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC;QACvB,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC,EAC1B,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,EACzB,QAAQ,CACT,CAAC;AACJ,CAAC;AAMD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAA2B;IAC7D,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,QAAQ;YACX,OAAO,CAAC,CAAC,eAAe,EAAE,CAAC;QAC7B,KAAK,SAAS;YACZ,OAAO,CAAC,CAAC,gBAAgB,EAAE,CAAC;QAC9B,KAAK,QAAQ;YACX,OAAO,CAAC,CAAC,eAAe,EAAE,CAAC;QAC7B,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,CAAC,GAAU,IAAI,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,EAAE,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,GAAyB;IACnD,OAAO,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC;AACxE,CAAC","sourcesContent":["import * as recast from \"recast\";\nimport type { ManifestExtraInput } from \"../../types/application-manifest.js\";\n\nconst b = recast.types.builders;\n\nexport type TSInterfaceBody = Parameters<typeof b.tsInterfaceBody>[0];\n\n/**\n * Builds an import statement with named imports.\n *\n * @example\n *\n * ```ts\n * buildImportStatement(\n * [\"a\", \"b\"],\n * \"./path\",\n * );\n * // => import { a, b } from \"./path\";\n * ```\n */\nexport function buildImportStatement(\n specifiers: string[],\n source: string,\n importKind: \"type\" | \"value\" = \"value\"\n) {\n return b.importDeclaration(\n specifiers.map((s) => b.importSpecifier(b.identifier(s))),\n b.stringLiteral(source),\n importKind\n );\n}\n\ntype TSTypeAnnotation = Parameters<typeof b.tsTypeAnnotation>[0];\nconst VALID_IDENTIFIER = /^[$_a-zA-Z][a-zA-Z0-9_$]*$/;\n\n/**\n * Builds a key/value pair for use in a type. Automatically quotes the key if it\n * contains invalid JavaScript identifier characters.\n *\n * @example\n *\n * ```ts\n * buildPropertySignature(\n * \"key\"\n * b.tsLiteralType(b.tsStringKeyword())\n * );\n * // => key: string\n * ```\n */\nexport function buildPropertySignature(\n keyName: string,\n value: TSTypeAnnotation,\n optional = false\n) {\n return b.tsPropertySignature(\n VALID_IDENTIFIER.test(keyName) ?\n b.identifier(keyName)\n : b.stringLiteral(keyName),\n b.tsTypeAnnotation(value),\n optional\n );\n}\n\n// Type that tracks any reference to a type literal so that we can create an AST\n// node from it\ntype SupportedLiteralTypes = ManifestExtraInput[\"type\"];\n\n/**\n * Returns a TypeScript literal type from a string.\n *\n * @example\n * ```ts\n * buildKeywordLiteral(\"string\");\n * // => string\n *\n * buildKeywordLiteral(\"number\");\n * // => number\n * ````\n */\nexport function buildKeywordLiteral(type: SupportedLiteralTypes) {\n switch (type) {\n case \"string\":\n return b.tsStringKeyword();\n case \"boolean\":\n return b.tsBooleanKeyword();\n case \"number\":\n return b.tsNumberKeyword();\n default: {\n const _: never = type;\n throw new Error(`Unexpected input type: ${_}`);\n }\n }\n}\n\n/**\n * Pretty prints the TypeScript AST into a code string.\n */\nexport function printRecast(ast: recast.types.ASTNode) {\n return recast.prettyPrint(ast, { tabWidth: 2, quote: \"double\" }).code;\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.0",
4
+ "version": "0.6.1",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -100,7 +100,7 @@
100
100
  "build:src": "tsc --project tsconfig.src.build.json",
101
101
  "build:vite": "tsc --project tsconfig.vite.build.json",
102
102
  "copy-ts-configs": "copyfiles -u 1 \"src/tsconfig/*/tsconfig.json\" dist",
103
- "clean": "rimraf dist",
103
+ "clean": "rimraf dist *.tgz",
104
104
  "test": "vitest",
105
105
  "changeset": "knope document-change",
106
106
  "format": "prettier --write .",
@@ -126,7 +126,7 @@
126
126
  "@vitest/coverage-v8": "^4.0.13",
127
127
  "copyfiles": "^2.4.1",
128
128
  "esbuild": "^0.25.12",
129
- "graphql": "^16.9.0",
129
+ "graphql": "^16.12.0",
130
130
  "happy-dom": "^20.0.10",
131
131
  "memfs": "^4.56.10",
132
132
  "mock-require": "^3.0.3",
@@ -153,11 +153,15 @@
153
153
  }
154
154
  },
155
155
  "dependencies": {
156
+ "@graphql-codegen/cli": "^6.1.3",
157
+ "@graphql-codegen/typescript": "^5.0.9",
158
+ "@graphql-codegen/typescript-operations": "^5.0.9",
156
159
  "@graphql-tools/graphql-tag-pluck": "^8.3.23",
157
160
  "@wry/equality": "^0.5.7",
158
161
  "cosmiconfig": "^9.0.0",
159
162
  "crypto-hash": "^4.0.0",
160
163
  "glob": "^11.0.3",
164
+ "recast": "^0.23.11",
161
165
  "tslib": "^2.8.1",
162
166
  "zod": "^4.3.6"
163
167
  }
@@ -0,0 +1,32 @@
1
+ export interface Register {}
2
+
3
+ /**
4
+ * @deprecated Please use the `ToolInfo` type instead. `ToolName` will be
5
+ * removed in the next major version.
6
+ */
7
+ export type ToolName =
8
+ Register extends { toolName: infer T extends string } ? T : string;
9
+
10
+ type RegisteredToolInputs =
11
+ Register extends { toolInputs: infer T extends Record<string, unknown> } ? T
12
+ : never;
13
+
14
+ /**
15
+ * @deprecated Please use the `ToolInfo` type instead. `ToolInput` will be
16
+ * removed in the next major version.
17
+ */
18
+ export type ToolInput =
19
+ [RegisteredToolInputs] extends [never] ? Record<string, unknown>
20
+ : RegisteredToolInputs[keyof RegisteredToolInputs];
21
+
22
+ type ToolInfoFromInputs<T extends Record<string, unknown>> = {
23
+ [K in keyof T]: {
24
+ toolName: K;
25
+ toolInput: T[K] extends Record<string, never> ? T[K] | undefined : T[K];
26
+ };
27
+ }[keyof T];
28
+
29
+ export type ToolInfo =
30
+ [RegisteredToolInputs] extends [never] ?
31
+ { toolName: string; toolInput: Record<string, unknown> | undefined }
32
+ : ToolInfoFromInputs<RegisteredToolInputs>;
package/src/index.ts CHANGED
@@ -8,6 +8,13 @@ export type {
8
8
  ManifestWidgetSettings,
9
9
  } from "./types/application-manifest.js";
10
10
 
11
+ export type {
12
+ Register,
13
+ ToolInfo,
14
+ ToolInput,
15
+ ToolName,
16
+ } from "./core/typeRegistration.js";
17
+
11
18
  export { ApolloClient } from "./core/ApolloClient.js";
12
19
  export { ToolCallLink } from "./link/ToolCallLink.js";
13
20
 
@@ -0,0 +1,53 @@
1
+ import { test, expect } from "vitest";
2
+ import {
3
+ disableActEnvironment,
4
+ renderHookToSnapshotStream,
5
+ } from "@testing-library/react-render-stream";
6
+ import { Suspense } from "react";
7
+ import { InMemoryCache } from "@apollo/client";
8
+
9
+ import { useToolInfo } from "../useToolInfo.js";
10
+ import { ApolloClient } from "../../../core/ApolloClient.js";
11
+ import {
12
+ graphqlToolResult,
13
+ minimalHostContextWithToolName,
14
+ mockApplicationManifest,
15
+ mockMcpHost,
16
+ spyOnConsole,
17
+ } from "../../../../testing/internal/index.js";
18
+ import { ApolloProvider } from "../../../../react/ApolloProvider.js";
19
+
20
+ test("returns tool name and input combined", async () => {
21
+ using _ = spyOnConsole("debug");
22
+ const client = new ApolloClient({
23
+ cache: new InMemoryCache(),
24
+ manifest: mockApplicationManifest(),
25
+ });
26
+
27
+ using host = await mockMcpHost({
28
+ hostContext: minimalHostContextWithToolName("GetProduct"),
29
+ });
30
+ host.onCleanup(() => client.stop());
31
+
32
+ host.sendToolInput({ arguments: { id: "1" } });
33
+ host.sendToolResult(graphqlToolResult({ data: { product: null } }));
34
+
35
+ using _disabledAct = disableActEnvironment();
36
+ const { takeSnapshot } = await renderHookToSnapshotStream(
37
+ () => useToolInfo(),
38
+ {
39
+ wrapper: ({ children }) => (
40
+ <Suspense>
41
+ <ApolloProvider client={client}>{children}</ApolloProvider>
42
+ </Suspense>
43
+ ),
44
+ }
45
+ );
46
+
47
+ await expect(takeSnapshot()).resolves.toEqual({
48
+ toolName: "GetProduct",
49
+ toolInput: { id: "1" },
50
+ });
51
+
52
+ await expect(takeSnapshot).not.toRerender();
53
+ });
@@ -0,0 +1,13 @@
1
+ import type { ToolInfo } from "../../../core/typeRegistration.js";
2
+ import { useApolloClient } from "./useApolloClient.js";
3
+
4
+ export function useToolInfo(): ToolInfo | undefined {
5
+ const appManager = useApolloClient()["appManager"];
6
+ const toolName = appManager.toolName;
7
+
8
+ if (!toolName) {
9
+ return;
10
+ }
11
+
12
+ return { toolName, toolInput: appManager.toolInput };
13
+ }
@@ -1,5 +1,10 @@
1
+ import type { ToolInput } from "../../../core/typeRegistration.js";
1
2
  import { useApolloClient } from "./useApolloClient.js";
2
3
 
3
- export function useToolInput() {
4
+ /**
5
+ * @deprecated Please use the `useToolInfo` hook. `useToolInput` will be removed
6
+ * in the next major version.
7
+ */
8
+ export function useToolInput(): ToolInput | undefined {
4
9
  return useApolloClient()["appManager"].toolInput;
5
10
  }
@@ -1,5 +1,10 @@
1
+ import type { ToolName } from "../../../core/typeRegistration.js";
1
2
  import { useApolloClient } from "./useApolloClient.js";
2
3
 
3
- export function useToolName() {
4
+ /**
5
+ * @deprecated Please use the `useToolInfo` hook. `useToolName` will be removed
6
+ * in the next major version.
7
+ */
8
+ export function useToolName(): ToolName | undefined {
4
9
  return useApolloClient()["appManager"].toolName;
5
10
  }
@@ -3,4 +3,5 @@ export { useHostContext } from "./hooks/useHostContext.js";
3
3
  export { useToolName } from "./hooks/useToolName.js";
4
4
  export { useToolMetadata } from "./hooks/useToolMetadata.js";
5
5
  export { useToolInput } from "./hooks/useToolInput.js";
6
+ export { useToolInfo } from "./hooks/useToolInfo.js";
6
7
  export { createHydrationUtils } from "./hooks/createHydrationUtils.js";
@@ -0,0 +1,92 @@
1
+ import { afterEach, expect, test, vi } from "vitest";
2
+ import {
3
+ graphqlToolResult,
4
+ minimalHostContextWithToolName,
5
+ mockApplicationManifest,
6
+ mockMcpHost,
7
+ spyOnConsole,
8
+ stubOpenAiGlobals,
9
+ } from "../../../../testing/internal/index.js";
10
+ import {
11
+ disableActEnvironment,
12
+ renderHookToSnapshotStream,
13
+ } from "@testing-library/react-render-stream";
14
+ import { useToolInfo } from "../useToolInfo.js";
15
+ import { ApolloClient } from "../../../core/ApolloClient.js";
16
+ import { InMemoryCache } from "@apollo/client";
17
+ import { Suspense } from "react";
18
+ import { ApolloProvider } from "../../../../react/ApolloProvider.js";
19
+
20
+ afterEach(() => {
21
+ vi.unstubAllGlobals();
22
+ });
23
+
24
+ test("returns tool name and input combined", async () => {
25
+ using _ = spyOnConsole("debug");
26
+ stubOpenAiGlobals({ toolResponseMetadata: {}, toolInput: { id: "1" } });
27
+ const client = new ApolloClient({
28
+ cache: new InMemoryCache(),
29
+ manifest: mockApplicationManifest(),
30
+ });
31
+
32
+ using host = await mockMcpHost({
33
+ hostContext: minimalHostContextWithToolName("GetProduct"),
34
+ });
35
+ host.onCleanup(() => client.stop());
36
+
37
+ host.sendToolInput({ arguments: { id: "1" } });
38
+ host.sendToolResult(graphqlToolResult({ data: { product: null } }));
39
+
40
+ using _disabledAct = disableActEnvironment();
41
+ const { takeSnapshot } = await renderHookToSnapshotStream(
42
+ () => useToolInfo(),
43
+ {
44
+ wrapper: ({ children }) => (
45
+ <Suspense>
46
+ <ApolloProvider client={client}>{children}</ApolloProvider>
47
+ </Suspense>
48
+ ),
49
+ }
50
+ );
51
+
52
+ await expect(takeSnapshot()).resolves.toEqual({
53
+ toolName: "GetProduct",
54
+ toolInput: { id: "1" },
55
+ });
56
+ await expect(takeSnapshot).not.toRerender();
57
+ });
58
+
59
+ test("returns undefined toolInput when toolInput is not provided", async () => {
60
+ using _ = spyOnConsole("debug");
61
+ stubOpenAiGlobals({ toolResponseMetadata: {} });
62
+ const client = new ApolloClient({
63
+ cache: new InMemoryCache(),
64
+ manifest: mockApplicationManifest(),
65
+ });
66
+
67
+ using host = await mockMcpHost({
68
+ hostContext: minimalHostContextWithToolName("GetProduct"),
69
+ });
70
+ host.onCleanup(() => client.stop());
71
+
72
+ host.sendToolInput({ arguments: {} });
73
+ host.sendToolResult(graphqlToolResult({ data: { product: null } }));
74
+
75
+ using _disabledAct = disableActEnvironment();
76
+ const { takeSnapshot } = await renderHookToSnapshotStream(
77
+ () => useToolInfo(),
78
+ {
79
+ wrapper: ({ children }) => (
80
+ <Suspense>
81
+ <ApolloProvider client={client}>{children}</ApolloProvider>
82
+ </Suspense>
83
+ ),
84
+ }
85
+ );
86
+
87
+ await expect(takeSnapshot()).resolves.toEqual({
88
+ toolName: "GetProduct",
89
+ toolInput: undefined,
90
+ });
91
+ await expect(takeSnapshot).not.toRerender();
92
+ });