@belgie/mcp 0.1.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codegen-DnMS1wg_.js","names":["#redirectUrl","#metadata","#state","#openBrowser","#clientInformation","#tokens","#codeVerifier","#uses","#rootName","#definitions","#definitionNames"],"sources":["../src/oauth.ts","../src/schema.ts","../src/codegen.ts"],"sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createServer, type Server } from \"node:http\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientInformationMixed,\n OAuthClientMetadata,\n OAuthTokens,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\nconst CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;\n\ntype CallbackServer = {\n redirectUrl: string;\n waitForCode: () => Promise<string>;\n close: () => Promise<void>;\n};\n\nexport class MemoryOAuthProvider implements OAuthClientProvider {\n readonly #redirectUrl: string;\n readonly #metadata: OAuthClientMetadata;\n readonly #state: string;\n readonly #openBrowser: boolean;\n #clientInformation: OAuthClientInformationMixed | undefined;\n #tokens: OAuthTokens | undefined;\n #codeVerifier: string | undefined;\n\n constructor(options: {\n redirectUrl: string;\n state: string;\n openBrowser: boolean;\n }) {\n this.#redirectUrl = options.redirectUrl;\n this.#state = options.state;\n this.#openBrowser = options.openBrowser;\n this.#metadata = {\n client_name: \"Belgie MCP Tool Codegen\",\n redirect_uris: [options.redirectUrl],\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n };\n }\n\n get redirectUrl(): string {\n return this.#redirectUrl;\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return this.#metadata;\n }\n\n state(): string {\n return this.#state;\n }\n\n clientInformation(): OAuthClientInformationMixed | undefined {\n return this.#clientInformation;\n }\n\n saveClientInformation(clientInformation: OAuthClientInformationMixed): void {\n this.#clientInformation = clientInformation;\n }\n\n tokens(): OAuthTokens | undefined {\n return this.#tokens;\n }\n\n saveTokens(tokens: OAuthTokens): void {\n this.#tokens = tokens;\n }\n\n async redirectToAuthorization(authorizationUrl: URL): Promise<void> {\n if (!this.#openBrowser) {\n process.stderr.write(`Authorize MCP code generation at:\\n${authorizationUrl.toString()}\\n`);\n return;\n }\n const { default: open } = await import(\"open\");\n await open(authorizationUrl.toString());\n }\n\n saveCodeVerifier(codeVerifier: string): void {\n this.#codeVerifier = codeVerifier;\n }\n\n codeVerifier(): string {\n if (this.#codeVerifier === undefined) {\n throw new Error(\"OAuth code verifier was not saved\");\n }\n return this.#codeVerifier;\n }\n}\n\nfunction closeServer(server: Server): Promise<void> {\n if (!server.listening) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n server.close((error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n}\n\nexport async function startOAuthCallbackServer(state: string): Promise<CallbackServer> {\n let resolveCode: ((code: string) => void) | undefined;\n let rejectCode: ((error: Error) => void) | undefined;\n const codePromise = new Promise<string>((resolve, reject) => {\n resolveCode = resolve;\n rejectCode = reject;\n });\n\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n if (url.pathname !== \"/callback\") {\n response.writeHead(404).end(\"Not found\");\n return;\n }\n if (url.searchParams.get(\"state\") !== state) {\n response.writeHead(400, { \"content-type\": \"text/plain; charset=utf-8\" });\n response.end(\"Invalid OAuth state\");\n return;\n }\n if (url.searchParams.has(\"error\")) {\n const description = url.searchParams.get(\"error_description\");\n const error = url.searchParams.get(\"error\")!;\n response.writeHead(400, { \"content-type\": \"text/plain; charset=utf-8\" });\n response.end(\"OAuth authorization failed\");\n rejectCode?.(new Error(description ? `${error}: ${description}` : error));\n return;\n }\n const code = url.searchParams.get(\"code\");\n if (code === null || code.length === 0) {\n response.writeHead(400, { \"content-type\": \"text/plain; charset=utf-8\" });\n response.end(\"Missing OAuth authorization code\");\n rejectCode?.(new Error(\"Missing OAuth authorization code\"));\n return;\n }\n response.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\" });\n response.end(\n \"<!doctype html><title>Belgie MCP authorization complete</title><p>Authorization complete. You can close this window.</p>\",\n );\n resolveCode?.(code);\n });\n\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error) => {\n server.off(\"listening\", onListening);\n reject(error);\n };\n const onListening = () => {\n server.off(\"error\", onError);\n resolve();\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(0, \"127.0.0.1\");\n });\n\n const address = server.address();\n if (address === null || typeof address === \"string\") {\n await closeServer(server);\n throw new Error(\"OAuth callback server did not expose a loopback port\");\n }\n\n return {\n redirectUrl: `http://127.0.0.1:${address.port}/callback`,\n waitForCode: async () => {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => {\n reject(new Error(\"Timed out waiting for the OAuth callback\"));\n }, CALLBACK_TIMEOUT_MS);\n });\n try {\n return await Promise.race([codePromise, timeoutPromise]);\n } finally {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n }\n },\n close: () => closeServer(server),\n };\n}\n\nexport function oauthState(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n","type JsonObject = Record<string, unknown>;\ntype JsonSchema = boolean | JsonObject;\n\nconst UNSUPPORTED_KEYWORDS = [\n \"contains\",\n \"dependencies\",\n \"dependentSchemas\",\n \"definitions\",\n \"else\",\n \"if\",\n \"not\",\n \"patternProperties\",\n \"then\",\n \"unevaluatedItems\",\n \"unevaluatedProperties\",\n] as const;\n\nconst ANNOTATION_KEYWORDS = new Set([\n \"$comment\",\n \"$defs\",\n \"$id\",\n \"$schema\",\n \"default\",\n \"deprecated\",\n \"description\",\n \"examples\",\n \"readOnly\",\n \"title\",\n \"writeOnly\",\n]);\n\nconst STRUCTURAL_KEYWORDS = new Set([\n \"$ref\",\n \"additionalItems\",\n \"additionalProperties\",\n \"allOf\",\n \"anyOf\",\n \"const\",\n \"enum\",\n \"items\",\n \"nullable\",\n \"oneOf\",\n \"prefixItems\",\n \"properties\",\n \"required\",\n \"type\",\n]);\n\nconst RESERVED_VALUE_IDENTIFIERS = new Set([\n \"abstract\",\n \"any\",\n \"arguments\",\n \"as\",\n \"asserts\",\n \"await\",\n \"bigint\",\n \"boolean\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"declare\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"infer\",\n \"intrinsic\",\n \"instanceof\",\n \"interface\",\n \"is\",\n \"keyof\",\n \"let\",\n \"module\",\n \"namespace\",\n \"never\",\n \"new\",\n \"null\",\n \"number\",\n \"object\",\n \"out\",\n \"override\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"readonly\",\n \"require\",\n \"return\",\n \"satisfies\",\n \"set\",\n \"static\",\n \"string\",\n \"super\",\n \"switch\",\n \"symbol\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"type\",\n \"typeof\",\n \"undefined\",\n \"unique\",\n \"unknown\",\n \"using\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n]);\n\nexport class IdentifierAllocator {\n readonly #uses = new Map<string, number>();\n\n allocate(preferred: string): string {\n const safe = identifier(preferred);\n const count = (this.#uses.get(safe) ?? 0) + 1;\n this.#uses.set(safe, count);\n return count === 1 ? safe : `${safe}${count}`;\n }\n}\n\nexport class ValueIdentifierAllocator {\n readonly #uses = new Map<string, number>();\n\n allocate(value: string): string {\n const safe = valueIdentifier(value);\n const count = (this.#uses.get(safe) ?? 0) + 1;\n this.#uses.set(safe, count);\n return count === 1 ? safe : `${safe}${count}`;\n }\n}\n\nexport type CompiledSchema = {\n declarations: string[];\n rootName: string;\n};\n\nfunction isObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaObject(value: unknown, location: string): JsonObject {\n if (!isObject(value)) {\n throw new Error(`${location} must be a JSON Schema object`);\n }\n return value;\n}\n\nfunction schemaArray(value: unknown, location: string): JsonSchema[] {\n if (!Array.isArray(value)) {\n throw new Error(`${location} must be an array of JSON Schemas`);\n }\n return value.map((item, index) => {\n if (typeof item !== \"boolean\" && !isObject(item)) {\n throw new Error(`${location}[${index}] must be a JSON Schema`);\n }\n return item;\n });\n}\n\nfunction identifierWords(value: string): string[] {\n return value.match(/[\\p{L}\\p{N}]+/gu) ?? [];\n}\n\nfunction identifier(value: string): string {\n const words = identifierWords(value);\n const joined = words\n .map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`)\n .join(\"\");\n const result = joined || \"Schema\";\n return /^\\p{N}/u.test(result) ? `Schema${result}` : result;\n}\n\nfunction valueIdentifier(value: string): string {\n const words = identifierWords(value);\n let result = words\n .map((word, index) => {\n const first = word.slice(0, 1);\n const rest = word.slice(1);\n return index === 0\n ? `${first.toLocaleLowerCase(\"en-US\")}${rest}`\n : `${first.toLocaleUpperCase(\"en-US\")}${rest}`;\n })\n .join(\"\");\n if (!result) {\n result = \"tool\";\n } else if (/^\\p{N}/u.test(result)) {\n result = `tool${result}`;\n } else if (RESERVED_VALUE_IDENTIFIERS.has(result)) {\n result = `tool${result.slice(0, 1).toLocaleUpperCase(\"en-US\")}${result.slice(1)}`;\n }\n return result;\n}\n\nexport function typeIdentifier(value: string): string {\n return identifier(value);\n}\n\nfunction decodePointer(value: string): string {\n return decodeURIComponent(value).replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n}\n\nfunction union(types: string[]): string {\n const unique = [...new Set(types)];\n if (unique.includes(\"unknown\")) {\n return \"unknown\";\n }\n return unique.length === 0\n ? \"never\"\n : unique\n .map((type) => (hasTopLevelOperator(type, \" & \") ? `(${type})` : type))\n .join(\" | \");\n}\n\nfunction intersection(types: string[]): string {\n const unique = [...new Set(types.filter((type) => type !== \"unknown\"))];\n if (unique.includes(\"never\")) {\n return \"never\";\n }\n if (unique.length <= 1) {\n return unique[0] ?? \"unknown\";\n }\n return unique.map((type) => parenthesize(type)).join(\" & \");\n}\n\nfunction parenthesize(type: string): string {\n return hasTopLevelOperator(type, \" | \") ? `(${type})` : type;\n}\n\nfunction arrayElement(type: string): string {\n return hasTopLevelOperator(type, \" | \") || hasTopLevelOperator(type, \" & \")\n ? `(${type})`\n : type;\n}\n\nfunction hasTopLevelOperator(type: string, operator: string): boolean {\n let depth = 0;\n let quote: string | undefined;\n for (let index = 0; index < type.length; index += 1) {\n const character = type[index]!;\n if (quote !== undefined) {\n if (character === \"\\\\\") {\n index += 1;\n } else if (character === quote) {\n quote = undefined;\n }\n continue;\n }\n if (character === '\"' || character === \"'\") {\n quote = character;\n } else if (character === \"{\" || character === \"[\" || character === \"(\") {\n depth += 1;\n } else if (character === \"}\" || character === \"]\" || character === \")\") {\n depth -= 1;\n } else if (depth === 0 && type.startsWith(operator, index)) {\n return true;\n }\n }\n return false;\n}\n\nfunction indentType(type: string, spaces: number): string {\n return type.replaceAll(\"\\n\", `\\n${\" \".repeat(spaces)}`);\n}\n\nfunction literal(value: unknown, location: string): string {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(`${location} contains a non-finite number`);\n }\n return String(value);\n }\n if (Array.isArray(value)) {\n return `readonly [${value\n .map((item, index) => literal(item, `${location}[${index}]`))\n .join(\", \")}]`;\n }\n if (isObject(value)) {\n const properties = Object.keys(value)\n .sort()\n .map((key) => `readonly ${JSON.stringify(key)}: ${literal(value[key], `${location}.${key}`)}`);\n return `{ ${properties.join(\"; \")} }`;\n }\n throw new Error(`${location} is not a JSON value`);\n}\n\nfunction strip(schema: JsonObject, keys: Set<string>): JsonObject {\n return Object.fromEntries(Object.entries(schema).filter(([key]) => !keys.has(key)));\n}\n\nfunction hasStructuralKeywords(schema: JsonObject): boolean {\n return Object.keys(schema).some((key) => STRUCTURAL_KEYWORDS.has(key));\n}\n\nclass SchemaCompiler {\n readonly #rootName: string;\n readonly #definitions: Map<string, JsonSchema>;\n readonly #definitionNames: Map<string, string>;\n\n constructor(\n rootName: string,\n schema: JsonObject,\n allocator: IdentifierAllocator,\n ) {\n this.#rootName = rootName;\n const definitionsValue = schema.$defs;\n if (definitionsValue === undefined) {\n this.#definitions = new Map();\n } else {\n const definitions = schemaObject(definitionsValue, \"$defs\");\n this.#definitions = new Map(\n Object.keys(definitions)\n .sort()\n .map((name) => {\n const value = definitions[name];\n if (typeof value !== \"boolean\" && !isObject(value)) {\n throw new Error(`$defs.${name} must be a JSON Schema`);\n }\n return [name, value] as const;\n }),\n );\n }\n this.#definitionNames = new Map(\n [...this.#definitions].map(([name]) => [\n name,\n allocator.allocate(`${rootName}${identifier(name)}`),\n ]),\n );\n }\n\n declarations(schema: JsonObject): string[] {\n const rootSchema = { ...schema };\n delete rootSchema.$defs;\n const declarations = [`export type ${this.#rootName} = ${this.compile(rootSchema, this.#rootName)};`];\n for (const [name, definition] of this.#definitions) {\n declarations.push(\n `export type ${this.#definitionNames.get(name)!} = ${this.compile(\n definition,\n `$defs.${name}`,\n )};`,\n );\n }\n return declarations;\n }\n\n compile(schema: JsonSchema, location: string): string {\n if (schema === true) {\n return \"unknown\";\n }\n if (schema === false) {\n return \"never\";\n }\n for (const keyword of UNSUPPORTED_KEYWORDS) {\n if (keyword in schema) {\n throw new Error(`${location} uses unsupported JSON Schema keyword ${JSON.stringify(keyword)}`);\n }\n }\n\n const parts: string[] = [];\n if (schema.$ref !== undefined) {\n parts.push(this.reference(schema.$ref, location));\n const rest = strip(schema, new Set([\"$ref\", ...ANNOTATION_KEYWORDS]));\n if (hasStructuralKeywords(rest)) {\n parts.push(this.compile(rest, location));\n }\n return this.nullable(intersection(parts), schema);\n }\n\n if (schema.const !== undefined) {\n parts.push(literal(schema.const, `${location}.const`));\n } else if (schema.enum !== undefined) {\n if (!Array.isArray(schema.enum) || schema.enum.length === 0) {\n throw new Error(`${location}.enum must be a non-empty array`);\n }\n parts.push(\n union(schema.enum.map((item, index) => literal(item, `${location}.enum[${index}]`))),\n );\n }\n\n for (const keyword of [\"oneOf\", \"anyOf\"] as const) {\n if (schema[keyword] !== undefined) {\n parts.push(\n union(\n schemaArray(schema[keyword], `${location}.${keyword}`).map((item, index) =>\n this.compile(item, `${location}.${keyword}[${index}]`),\n ),\n ),\n );\n }\n }\n if (schema.allOf !== undefined) {\n parts.push(\n intersection(\n schemaArray(schema.allOf, `${location}.allOf`).map((item, index) =>\n this.compile(item, `${location}.allOf[${index}]`),\n ),\n ),\n );\n }\n\n const typeSchema = strip(\n schema,\n new Set([\"allOf\", \"anyOf\", \"const\", \"enum\", \"nullable\", \"oneOf\", ...ANNOTATION_KEYWORDS]),\n );\n if (typeSchema.type !== undefined) {\n parts.push(this.explicitType(typeSchema, location));\n } else if (\n typeSchema.properties !== undefined ||\n typeSchema.additionalProperties !== undefined ||\n typeSchema.required !== undefined\n ) {\n parts.push(this.object(typeSchema, location));\n } else if (typeSchema.items !== undefined || typeSchema.prefixItems !== undefined) {\n parts.push(this.array(typeSchema, location));\n }\n\n const result = intersection(parts);\n return this.nullable(result, schema);\n }\n\n explicitType(schema: JsonObject, location: string): string {\n const value = schema.type;\n const types = Array.isArray(value) ? value : [value];\n if (types.length === 0 || types.some((type) => typeof type !== \"string\")) {\n throw new Error(`${location}.type must be a string or non-empty string array`);\n }\n return union(types.map((type) => this.singleType(type as string, schema, location)));\n }\n\n singleType(type: string, schema: JsonObject, location: string): string {\n switch (type) {\n case \"array\":\n return this.array(schema, location);\n case \"boolean\":\n return \"boolean\";\n case \"integer\":\n case \"number\":\n return \"number\";\n case \"null\":\n return \"null\";\n case \"object\":\n return this.object(schema, location);\n case \"string\":\n return \"string\";\n default:\n throw new Error(`${location}.type contains unsupported type ${JSON.stringify(type)}`);\n }\n }\n\n object(schema: JsonObject, location: string): string {\n const propertiesValue = schema.properties;\n const properties =\n propertiesValue === undefined ? {} : schemaObject(propertiesValue, `${location}.properties`);\n const requiredValue = schema.required;\n if (\n requiredValue !== undefined &&\n (!Array.isArray(requiredValue) || requiredValue.some((item) => typeof item !== \"string\"))\n ) {\n throw new Error(`${location}.required must be an array of property names`);\n }\n const required = new Set((requiredValue as string[] | undefined) ?? []);\n for (const name of required) {\n if (!(name in properties)) {\n throw new Error(`${location}.required references missing property ${JSON.stringify(name)}`);\n }\n }\n\n const propertyTypes: string[] = [];\n let hasOptional = false;\n const members = Object.keys(properties)\n .sort()\n .map((name) => {\n const property = properties[name];\n if (typeof property !== \"boolean\" && !isObject(property)) {\n throw new Error(`${location}.properties.${name} must be a JSON Schema`);\n }\n const optional = !required.has(name);\n if (optional) {\n hasOptional = true;\n }\n const propertyType = this.compile(property, `${location}.properties.${name}`);\n propertyTypes.push(propertyType);\n return ` ${JSON.stringify(name)}${optional ? \"?\" : \"\"}: ${indentType(propertyType, 2)};`;\n });\n const objectType =\n members.length === 0 ? \"Record<string, never>\" : `{\\n${members.join(\"\\n\")}\\n}`;\n\n const additional = schema.additionalProperties;\n if (additional === undefined || additional === false) {\n return objectType;\n }\n const valueType =\n additional === true\n ? \"unknown\"\n : this.compile(\n schemaObject(additional, `${location}.additionalProperties`),\n `${location}.additionalProperties`,\n );\n if (members.length === 0) {\n return `Record<string, ${valueType}>`;\n }\n // Index signature must accept every named field type (and undefined if any are optional).\n const indexTypes = [...propertyTypes, valueType];\n if (hasOptional) {\n indexTypes.push(\"undefined\");\n }\n const indexType = union(indexTypes);\n return `{\\n${members.join(\"\\n\")}\\n [key: string]: ${indentType(indexType, 2)};\\n}`;\n }\n\n array(schema: JsonObject, location: string): string {\n if (schema.prefixItems !== undefined) {\n const prefixItems = schemaArray(schema.prefixItems, `${location}.prefixItems`);\n const elements = prefixItems.map((item, index) =>\n this.compile(item, `${location}.prefixItems[${index}]`),\n );\n const rest = schema.items;\n const fixedLength = schema.maxItems === prefixItems.length;\n if (!fixedLength && rest !== false) {\n const restType =\n rest === undefined || rest === true\n ? \"unknown\"\n : this.compile(schemaObject(rest, `${location}.items`), `${location}.items`);\n elements.push(`...${arrayElement(restType)}[]`);\n }\n return `readonly [${elements.join(\", \")}]`;\n }\n const items = schema.items;\n if (Array.isArray(items)) {\n const elements = schemaArray(items, `${location}.items`).map((item, index) =>\n this.compile(item, `${location}.items[${index}]`),\n );\n const additional = schema.additionalItems;\n const fixedLength = schema.maxItems === elements.length;\n if (!fixedLength && additional !== false) {\n const restType =\n additional === undefined || additional === true\n ? \"unknown\"\n : this.compile(\n schemaObject(additional, `${location}.additionalItems`),\n `${location}.additionalItems`,\n );\n elements.push(`...${arrayElement(restType)}[]`);\n }\n return `readonly [${elements.join(\", \")}]`;\n }\n if (schema.additionalItems !== undefined) {\n throw new Error(\n `${location} uses additionalItems without a tuple-form items schema`,\n );\n }\n if (items === undefined || items === true) {\n return \"readonly unknown[]\";\n }\n if (items === false) {\n return \"readonly never[]\";\n }\n return `readonly ${arrayElement(\n this.compile(schemaObject(items, `${location}.items`), `${location}.items`),\n )}[]`;\n }\n\n reference(value: unknown, location: string): string {\n if (typeof value !== \"string\") {\n throw new Error(`${location}.$ref must be a string`);\n }\n if (value === \"#\") {\n return this.#rootName;\n }\n const prefix = \"#/$defs/\";\n if (!value.startsWith(prefix)) {\n throw new Error(`${location} contains unsupported external or non-$defs reference ${JSON.stringify(value)}`);\n }\n const name = decodePointer(value.slice(prefix.length));\n const reference = this.#definitionNames.get(name);\n if (reference === undefined) {\n throw new Error(`${location} references missing $defs entry ${JSON.stringify(name)}`);\n }\n return reference;\n }\n\n nullable(type: string, schema: JsonObject): string {\n return schema.nullable === true ? union([type, \"null\"]) : type;\n }\n}\n\nexport function compileSchema(\n schema: unknown,\n rootName: string,\n allocator: IdentifierAllocator,\n): CompiledSchema {\n const root = schemaObject(schema, rootName);\n const compiler = new SchemaCompiler(rootName, root, allocator);\n return {\n declarations: compiler.declarations(root),\n rootName,\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { UnauthorizedError } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { Tool } from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\n\nimport {\n MemoryOAuthProvider,\n oauthState,\n startOAuthCallbackServer,\n} from \"./oauth\";\nimport {\n compileSchema,\n IdentifierAllocator,\n typeIdentifier,\n ValueIdentifierAllocator,\n} from \"./schema\";\n\nexport type GenerateToolTypesOptions = {\n url: string | URL;\n headers?: Readonly<Record<string, string>>;\n oauth?: boolean;\n openBrowser?: boolean;\n};\n\ntype ToolNames = {\n call: string;\n input: string;\n output: string;\n};\n\ntype OutputSchema = NonNullable<Tool[\"outputSchema\"]>;\ntype ZodJsonSchema = Parameters<typeof z.fromJSONSchema>[0];\n\nfunction endpoint(value: string | URL): URL {\n let url: URL;\n try {\n url = value instanceof URL ? new URL(value) : new URL(value);\n } catch (cause: unknown) {\n throw new Error(`Invalid MCP URL ${JSON.stringify(String(value))}`, { cause });\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new Error(`MCP URL must use http or https, received ${JSON.stringify(url.protocol)}`);\n }\n if (url.username || url.password) {\n throw new Error(\"MCP URL must not contain credentials; use headers instead\");\n }\n return url;\n}\n\nfunction jsDoc(description: string): string[] {\n const sanitized = description.replaceAll(\"*/\", \"* /\").replaceAll(\"\\r\", \"\");\n const lines = sanitized.split(\"\\n\");\n if (lines.length === 1) {\n return [`/** ${lines[0]} */`];\n }\n return [\"/**\", ...lines.map((line) => ` * ${line}`), \" */\"];\n}\n\nfunction compareStrings(left: string, right: string): number {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalize(item));\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([left], [right]) => compareStrings(left, right))\n .map(([key, item]) => [key, canonicalize(item)]),\n );\n }\n return value;\n}\n\nfunction renderSchema(schema: OutputSchema): string[] {\n return JSON.stringify(canonicalize(schema), null, 2)\n .split(\"\\n\")\n .map((line) => ` ${line}`);\n}\n\nfunction compileToolSchema(\n tool: Tool,\n schemaName: \"inputSchema\" | \"outputSchema\",\n schema: unknown,\n rootName: string,\n allocator: IdentifierAllocator,\n): string[] {\n try {\n return compileSchema(schema, rootName, allocator).declarations;\n } catch (cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `MCP tool ${JSON.stringify(tool.name)} has an ${schemaName} TypeScript cannot compile: ${message}`,\n { cause },\n );\n }\n}\n\nfunction renderToolTypes(tools: Tool[]): string {\n const allocator = new IdentifierAllocator();\n const valueAllocator = new ValueIdentifierAllocator();\n const names = new Map<string, ToolNames>();\n for (const tool of tools) {\n const base = typeIdentifier(tool.name);\n names.set(tool.name, {\n call: valueAllocator.allocate(tool.name),\n input: allocator.allocate(`${base}Input`),\n output: allocator.allocate(`${base}Output`),\n });\n }\n\n let hasRawTools = false;\n let hasStructuredTools = false;\n const declarations: string[] = [];\n for (const tool of tools) {\n const toolNames = names.get(tool.name)!;\n declarations.push(\n ...compileToolSchema(\n tool,\n \"inputSchema\",\n tool.inputSchema,\n toolNames.input,\n allocator,\n ),\n );\n if (tool.outputSchema === undefined) {\n hasRawTools = true;\n declarations.push(`export type ${toolNames.output} = RawToolResult;`);\n } else {\n hasStructuredTools = true;\n try {\n z.fromJSONSchema(tool.outputSchema as ZodJsonSchema);\n } catch (cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new Error(\n `MCP tool ${JSON.stringify(tool.name)} has an outputSchema Zod cannot compile: ${message}`,\n { cause },\n );\n }\n declarations.push(\n ...compileToolSchema(\n tool,\n \"outputSchema\",\n tool.outputSchema,\n toolNames.output,\n allocator,\n ),\n );\n }\n }\n\n const calls: string[] = [];\n for (const tool of tools) {\n if (tool.description) {\n calls.push(...jsDoc(tool.description));\n }\n const toolNames = names.get(tool.name)!;\n if (tool.outputSchema === undefined) {\n calls.push(\n `export const ${toolNames.call} = createGeneratedRawTool<${toolNames.input}>(`,\n ` ${JSON.stringify(tool.name)},`,\n \");\",\n \"\",\n );\n } else {\n calls.push(\n `export const ${toolNames.call} = createGeneratedTool<${toolNames.input}, ${toolNames.output}>(`,\n ` ${JSON.stringify(tool.name)},`,\n ...renderSchema(tool.outputSchema),\n \");\",\n \"\",\n );\n }\n }\n\n const factoryImports = [\n ...(hasRawTools ? [\"createGeneratedRawTool\"] : []),\n ...(hasStructuredTools ? [\"createGeneratedTool\"] : []),\n ].join(\", \");\n\n return [\n ...(hasRawTools ? ['import type { RawToolResult } from \"@belgie/mcp\";'] : []),\n `import { ${factoryImports} } from \"@belgie/mcp/internal\";`,\n \"\",\n ...declarations.flatMap((declaration) => [declaration, \"\"]),\n ...calls,\n ].join(\"\\n\");\n}\n\nfunction createConnection(\n url: URL,\n headers: Readonly<Record<string, string>>,\n provider: MemoryOAuthProvider | undefined,\n) {\n const client = new Client(\n { name: \"belgie-mcp-codegen\", version: \"0.1.0\" },\n { capabilities: {} },\n );\n const transport = new StreamableHTTPClientTransport(url, {\n ...(provider === undefined ? {} : { authProvider: provider }),\n requestInit: { headers: new Headers(headers) },\n });\n return { client, transport };\n}\n\nasync function discoverTools(client: Client): Promise<Tool[]> {\n const tools = new Map<string, Tool>();\n const cursors = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = await client.listTools(cursor === undefined ? undefined : { cursor });\n for (const tool of page.tools) {\n if (tools.has(tool.name)) {\n throw new Error(`MCP server exposed duplicate tool name ${JSON.stringify(tool.name)}`);\n }\n tools.set(tool.name, tool);\n }\n cursor = page.nextCursor;\n if (cursor !== undefined && cursors.has(cursor)) {\n throw new Error(`MCP server repeated tools/list cursor ${JSON.stringify(cursor)}`);\n }\n if (cursor !== undefined) {\n cursors.add(cursor);\n }\n } while (cursor !== undefined);\n\n if (tools.size === 0) {\n throw new Error(\"MCP server exposed no tools\");\n }\n return [...tools.values()].sort((left, right) =>\n compareStrings(left.name, right.name),\n );\n}\n\nexport async function generateToolTypes(\n options: GenerateToolTypesOptions,\n): Promise<string> {\n const url = endpoint(options.url);\n const headers = options.headers ?? {};\n const useOAuth = options.oauth ?? true;\n const state = oauthState();\n const callback = useOAuth ? await startOAuthCallbackServer(state) : undefined;\n const provider =\n callback === undefined\n ? undefined\n : new MemoryOAuthProvider({\n redirectUrl: callback.redirectUrl,\n state,\n openBrowser: options.openBrowser ?? true,\n });\n let connection: ReturnType<typeof createConnection> | undefined;\n\n try {\n connection = createConnection(url, headers, provider);\n try {\n await connection.client.connect(connection.transport as Transport);\n } catch (cause: unknown) {\n if (!(cause instanceof UnauthorizedError) || provider === undefined || callback === undefined) {\n throw cause;\n }\n const code = await callback.waitForCode();\n await connection.transport.finishAuth(code);\n await connection.client.close();\n connection = createConnection(url, headers, provider);\n await connection.client.connect(connection.transport as Transport);\n }\n return renderToolTypes(await discoverTools(connection.client));\n } catch (cause: unknown) {\n if (cause instanceof Error) {\n throw new Error(`Failed to generate MCP tool types from ${url.toString()}: ${cause.message}`, {\n cause,\n });\n }\n throw cause;\n } finally {\n await Promise.allSettled([connection?.client.close(), callback?.close()]);\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,sBAAsB,MAAS;AAQrC,IAAa,sBAAb,MAAgE;CAC9D;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAIT;EACD,KAAKA,eAAe,QAAQ;EAC5B,KAAKE,SAAS,QAAQ;EACtB,KAAKC,eAAe,QAAQ;EAC5B,KAAKF,YAAY;GACf,aAAa;GACb,eAAe,CAAC,QAAQ,WAAW;GACnC,aAAa,CAAC,sB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,QAAQ,KAAK;EAC9C,aAAa,YAAY;GACvB,IAAI;GACJ,MAAM,iBAAiB,IAAI,SAAgB,UAAU,WAAW;IAC9D,UAAU,iBAAiB;KACzB,uBAAO,IAAI,MAAM,0CAA0C,CAAC;IAC9D,GAAG,mBAAmB;GACxB,CAAC;GACD,IAAI;IACF,OAAO,MAAM,QAAQ,KAAK,CAAC,aAAa,cAAc,CAAC;GACzD,UAAU;IACR,IAAI,YAAY,KAAA,GACd,aAAa,OAAO;GAExB;EACF;EACA,aAAa,YAAY,MAAM;CACjC;AACF;AAEA,SAAgB,aAAqB;CACnC,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;;;AC7LA,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,6CAA6B,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAa,sBAAb,MAAiC;CAC/B,wBAAiB,IAAI,IAAoB;CAEzC,SAAS,WAA2B;EAClC,MAAM,OAAO,WAAW,SAA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OAAO,QAAQ,WAAW,SAAsB;EACnE,SAAS,OAAgB;GACvB,IAAI,EAAE,iBAAiB,sBAAsB,aAAa,KAAA,KAAa,aAAa,KAAA,GAClF,MAAM;GAER,MAAM,OAAO,MAAM,SAAS,YAAY;GACxC,MAAM,WAAW,UAAU,WAAW,IAAI;GAC1C,MAAM,WAAW,OAAO,MAAM;GAC9B,aAAa,iBAAiB,KAAK,SAAS,QAAQ;GACpD,MAAM,WAAW,OAAO,QAAQ,WAAW,SAAsB;EACnE;EACA,OAAO,gBAAgB,MAAM,cAAc,WAAW,MAAM,CAAC;CAC/D,SAAS,OAAgB;EACvB,IAAI,iBAAiB,OACnB,MAAM,IAAI,MAAM,0CAA0C,IAAI,SAAS,EAAE,IAAI,MAAM,WAAW,EAC5F,MACF,CAAC;EAEH,MAAM;CACR,UAAU;EACR,MAAM,QAAQ,WAAW,CAAC,YAAY,OAAO,MAAM,GAAG,UAAU,MAAM,CAAC,CAAC;CAC1E;AACF"}
@@ -0,0 +1,11 @@
1
+ //#region src/codegen.d.ts
2
+ type GenerateToolTypesOptions = {
3
+ url: string | URL;
4
+ headers?: Readonly<Record<string, string>>;
5
+ oauth?: boolean;
6
+ openBrowser?: boolean;
7
+ };
8
+ declare function generateToolTypes(options: GenerateToolTypesOptions): Promise<string>;
9
+ //#endregion
10
+ export { GenerateToolTypesOptions, generateToolTypes };
11
+ //# sourceMappingURL=codegen.d.ts.map
@@ -0,0 +1,2 @@
1
+ import { t as generateToolTypes } from "./codegen-DnMS1wg_.js";
2
+ export { generateToolTypes };
@@ -0,0 +1,60 @@
1
+ import { a as RawToolResult, i as McpToolErrorResult, n as McpToolCancelledError, o as ToolCallError, r as McpToolError, s as ToolCallResult, t as ToolResultSource } from "./tool-result-source-niHoRYxM.js";
2
+ import { ComponentType, ReactNode } from "react";
3
+ import { App, AppEventMap, AppOptions, McpUiAppCapabilities } from "@modelcontextprotocol/ext-apps";
4
+ //#region src/widget-context.d.ts
5
+ declare function useWidget(): App;
6
+ //#endregion
7
+ //#region src/app.d.ts
8
+ declare function sendMessage(...args: Parameters<App["sendMessage"]>): ReturnType<App["sendMessage"]>;
9
+ declare function sendLog(...args: Parameters<App["sendLog"]>): ReturnType<App["sendLog"]>;
10
+ declare function updateModelContext(...args: Parameters<App["updateModelContext"]>): ReturnType<App["updateModelContext"]>;
11
+ declare function openLink(...args: Parameters<App["openLink"]>): ReturnType<App["openLink"]>;
12
+ declare function downloadFile(...args: Parameters<App["downloadFile"]>): ReturnType<App["downloadFile"]>;
13
+ declare function requestDisplayMode(...args: Parameters<App["requestDisplayMode"]>): ReturnType<App["requestDisplayMode"]>;
14
+ declare function requestTeardown(...args: Parameters<App["requestTeardown"]>): ReturnType<App["requestTeardown"]>;
15
+ //#endregion
16
+ //#region src/use-tool-result.d.ts
17
+ type ToolResultStatus = "pending" | "success" | "error";
18
+ type ToolResultState<Input extends object, Output> = {
19
+ data: Output | undefined;
20
+ error: ToolCallError | undefined;
21
+ rawResult: RawToolResult | undefined;
22
+ status: ToolResultStatus;
23
+ isLoading: boolean;
24
+ isFetching: boolean;
25
+ isSuccess: boolean;
26
+ isError: boolean;
27
+ execute: (input?: Input) => Promise<ToolCallResult<Output>>;
28
+ };
29
+ declare function useToolResult<Input extends object, Output>(source: ToolResultSource<Input, Output>): ToolResultState<Input, Output>;
30
+ //#endregion
31
+ //#region src/index.d.ts
32
+ type WidgetMetadata = {
33
+ name: string;
34
+ version: string;
35
+ title?: string;
36
+ capabilities?: McpUiAppCapabilities;
37
+ } & Pick<AppOptions, "autoResize" | "strict">;
38
+ type WidgetHooks = {
39
+ before?: () => void | Promise<void>;
40
+ after?: () => void | Promise<void>;
41
+ error?: (error: Error) => void;
42
+ toolInput?: (params: AppEventMap["toolinput"]) => void;
43
+ toolInputPartial?: (params: AppEventMap["toolinputpartial"]) => void;
44
+ toolResult?: (params: AppEventMap["toolresult"]) => void;
45
+ toolCancelled?: (params: AppEventMap["toolcancelled"]) => void;
46
+ hostContextChanged?: (params: AppEventMap["hostcontextchanged"]) => void;
47
+ teardown?: NonNullable<App["onteardown"]>;
48
+ };
49
+ type WidgetProps = {
50
+ metadata: WidgetMetadata;
51
+ children: ReactNode;
52
+ hooks?: WidgetHooks;
53
+ fallback?: ReactNode;
54
+ error?: ReactNode | ((error: Error) => ReactNode);
55
+ };
56
+ declare function Widget({ metadata, children, hooks, fallback, error: errorUI }: WidgetProps): string | number | bigint | boolean | import("react/jsx-runtime").JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | Iterable<ReactNode> | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | import("react").ReactPortal | null | undefined> | null | undefined;
57
+ declare function mountWidget(Widget: ComponentType): void;
58
+ //#endregion
59
+ export { McpToolCancelledError, McpToolError, type McpToolErrorResult, type RawToolResult, type ToolCallError, type ToolCallResult, type ToolResultState, type ToolResultStatus, Widget, WidgetHooks, WidgetMetadata, WidgetProps, downloadFile, mountWidget, openLink, requestDisplayMode, requestTeardown, sendLog, sendMessage, updateModelContext, useToolResult, useWidget };
60
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,312 @@
1
+ import { c as WidgetContext, d as getActiveWidget, f as useConnectedWidgetContext, i as getToolResultAdapter, l as activateWidget, o as McpToolCancelledError, p as useWidget, r as errorResult, s as McpToolError, u as deactivateWidget } from "./tool-result-source-DTFIKHfH.js";
2
+ import { StrictMode, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { App } from "@modelcontextprotocol/ext-apps";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ //#region src/app.ts
7
+ function sendMessage(...args) {
8
+ return getActiveWidget().sendMessage(...args);
9
+ }
10
+ function sendLog(...args) {
11
+ return getActiveWidget().sendLog(...args);
12
+ }
13
+ function updateModelContext(...args) {
14
+ return getActiveWidget().updateModelContext(...args);
15
+ }
16
+ function openLink(...args) {
17
+ return getActiveWidget().openLink(...args);
18
+ }
19
+ function downloadFile(...args) {
20
+ return getActiveWidget().downloadFile(...args);
21
+ }
22
+ function requestDisplayMode(...args) {
23
+ return getActiveWidget().requestDisplayMode(...args);
24
+ }
25
+ function requestTeardown(...args) {
26
+ return getActiveWidget().requestTeardown(...args);
27
+ }
28
+ //#endregion
29
+ //#region src/use-tool-result.ts
30
+ function sourceMismatchError(expectedName, actualName) {
31
+ if (actualName === void 0 || actualName === expectedName) return;
32
+ return /* @__PURE__ */ new Error(`useToolResult expected opening tool ${JSON.stringify(expectedName)}, received ${JSON.stringify(actualName)}`);
33
+ }
34
+ function openingSnapshot(adapter, lifecycle, mismatch) {
35
+ if (mismatch !== void 0) return {
36
+ data: void 0,
37
+ error: mismatch,
38
+ rawResult: lifecycle.rawResult,
39
+ status: "error",
40
+ isFetching: false
41
+ };
42
+ if (lifecycle.status === "pending") return {
43
+ data: void 0,
44
+ error: void 0,
45
+ rawResult: void 0,
46
+ status: "pending",
47
+ isFetching: true
48
+ };
49
+ if (lifecycle.status === "cancelled") return {
50
+ data: void 0,
51
+ error: new McpToolCancelledError(adapter.name, lifecycle.cancellationReason),
52
+ rawResult: void 0,
53
+ status: "error",
54
+ isFetching: false
55
+ };
56
+ const rawResult = lifecycle.rawResult;
57
+ const callResult = adapter.parse(rawResult);
58
+ return callResult.error === void 0 ? {
59
+ data: callResult.result,
60
+ error: void 0,
61
+ rawResult,
62
+ status: "success",
63
+ isFetching: false
64
+ } : {
65
+ data: void 0,
66
+ error: callResult.error,
67
+ rawResult,
68
+ status: "error",
69
+ isFetching: false
70
+ };
71
+ }
72
+ function useToolResult(source) {
73
+ const context = useConnectedWidgetContext("useToolResult");
74
+ const adapter = getToolResultAdapter(source);
75
+ const [hostToolName, setHostToolName] = useState(() => context.app.getHostContext()?.toolInfo?.tool.name);
76
+ const mismatch = useMemo(() => sourceMismatchError(adapter.name, hostToolName), [adapter.name, hostToolName]);
77
+ const [snapshot, setSnapshot] = useState(() => openingSnapshot(adapter, context.tool, mismatch));
78
+ const hasExecutedRef = useRef(false);
79
+ const hasExplicitInputRef = useRef(false);
80
+ const latestInputRef = useRef(context.tool.input);
81
+ const latestRequestRef = useRef(0);
82
+ const mountedRef = useRef(true);
83
+ useEffect(() => {
84
+ mountedRef.current = true;
85
+ return () => {
86
+ mountedRef.current = false;
87
+ latestRequestRef.current += 1;
88
+ };
89
+ }, []);
90
+ useEffect(() => {
91
+ const syncHostToolName = () => {
92
+ setHostToolName(context.app.getHostContext()?.toolInfo?.tool.name);
93
+ };
94
+ syncHostToolName();
95
+ context.app.addEventListener("hostcontextchanged", syncHostToolName);
96
+ return () => {
97
+ context.app.removeEventListener("hostcontextchanged", syncHostToolName);
98
+ };
99
+ }, [context.app]);
100
+ useEffect(() => {
101
+ if (!hasExplicitInputRef.current && context.tool.inputReceived) latestInputRef.current = context.tool.input;
102
+ }, [context.tool.input, context.tool.inputReceived]);
103
+ useEffect(() => {
104
+ if (!hasExecutedRef.current) setSnapshot(openingSnapshot(adapter, context.tool, mismatch));
105
+ }, [
106
+ adapter,
107
+ context.tool,
108
+ mismatch
109
+ ]);
110
+ const execute = useCallback(async function execute(input) {
111
+ hasExecutedRef.current = true;
112
+ if (arguments.length > 0) {
113
+ hasExplicitInputRef.current = true;
114
+ latestInputRef.current = input;
115
+ }
116
+ const request = ++latestRequestRef.current;
117
+ if (mismatch !== void 0) {
118
+ setSnapshot((current) => ({
119
+ ...current,
120
+ error: mismatch,
121
+ status: "error",
122
+ isFetching: false
123
+ }));
124
+ return errorResult(mismatch);
125
+ }
126
+ setSnapshot((current) => ({
127
+ ...current,
128
+ error: void 0,
129
+ status: current.data === void 0 ? "pending" : "success",
130
+ isFetching: true
131
+ }));
132
+ const execution = await adapter.execute(latestInputRef.current, context.app);
133
+ if (mountedRef.current && request === latestRequestRef.current) setSnapshot((current) => execution.callResult.error === void 0 ? {
134
+ data: execution.callResult.result,
135
+ error: void 0,
136
+ rawResult: execution.rawResult ?? current.rawResult,
137
+ status: "success",
138
+ isFetching: false
139
+ } : {
140
+ data: current.data,
141
+ error: execution.callResult.error,
142
+ rawResult: execution.rawResult ?? current.rawResult,
143
+ status: "error",
144
+ isFetching: false
145
+ });
146
+ return execution.callResult;
147
+ }, [
148
+ adapter,
149
+ context.app,
150
+ mismatch
151
+ ]);
152
+ return {
153
+ data: snapshot.data,
154
+ error: snapshot.error,
155
+ rawResult: snapshot.rawResult,
156
+ status: snapshot.status,
157
+ isLoading: snapshot.isFetching && snapshot.data === void 0,
158
+ isFetching: snapshot.isFetching,
159
+ isSuccess: snapshot.status === "success",
160
+ isError: snapshot.status === "error",
161
+ execute
162
+ };
163
+ }
164
+ //#endregion
165
+ //#region src/index.tsx
166
+ function applyHooks(app, hooks) {
167
+ app.onerror = hooks?.error ?? ((error) => console.error(error));
168
+ if (!hooks) return;
169
+ if (hooks.toolInput) app.addEventListener("toolinput", hooks.toolInput);
170
+ if (hooks.toolInputPartial) app.addEventListener("toolinputpartial", hooks.toolInputPartial);
171
+ if (hooks.toolResult) app.addEventListener("toolresult", hooks.toolResult);
172
+ if (hooks.toolCancelled) app.addEventListener("toolcancelled", hooks.toolCancelled);
173
+ if (hooks.hostContextChanged) app.addEventListener("hostcontextchanged", hooks.hostContextChanged);
174
+ }
175
+ function initialToolLifecycle() {
176
+ return {
177
+ input: void 0,
178
+ inputReceived: false,
179
+ rawResult: void 0,
180
+ cancellationReason: void 0,
181
+ status: "pending",
182
+ version: 0
183
+ };
184
+ }
185
+ let rootInstance = null;
186
+ function Widget({ metadata, children, hooks, fallback, error: errorUI }) {
187
+ const [connected, setConnected] = useState(false);
188
+ const [error, setError] = useState(null);
189
+ const [toolLifecycle, setToolLifecycle] = useState(initialToolLifecycle);
190
+ const appRef = useRef(null);
191
+ const initRef = useRef(null);
192
+ if (initRef.current == null) initRef.current = {
193
+ metadata,
194
+ hooks
195
+ };
196
+ useEffect(() => {
197
+ let cancelled = false;
198
+ let active = false;
199
+ const { metadata: meta, hooks: initHooks } = initRef.current;
200
+ const { capabilities, autoResize, strict, name, version, title } = meta;
201
+ const options = {};
202
+ if (autoResize !== void 0) options.autoResize = autoResize;
203
+ if (strict !== void 0) options.strict = strict;
204
+ const app = new App(title === void 0 ? {
205
+ name,
206
+ version
207
+ } : {
208
+ name,
209
+ version,
210
+ title
211
+ }, capabilities ?? {}, options);
212
+ appRef.current = app;
213
+ setToolLifecycle(initialToolLifecycle());
214
+ app.addEventListener("toolinput", (params) => {
215
+ if (!cancelled) setToolLifecycle((current) => ({
216
+ ...current,
217
+ input: params.arguments,
218
+ inputReceived: true
219
+ }));
220
+ });
221
+ app.addEventListener("toolresult", (params) => {
222
+ if (!cancelled) setToolLifecycle((current) => ({
223
+ ...current,
224
+ rawResult: params,
225
+ cancellationReason: void 0,
226
+ status: "result",
227
+ version: current.version + 1
228
+ }));
229
+ });
230
+ app.addEventListener("toolcancelled", (params) => {
231
+ if (!cancelled) setToolLifecycle((current) => ({
232
+ ...current,
233
+ rawResult: void 0,
234
+ cancellationReason: params.reason,
235
+ status: "cancelled",
236
+ version: current.version + 1
237
+ }));
238
+ });
239
+ applyHooks(app, initHooks);
240
+ app.onteardown = async (params, extra) => {
241
+ if (active) {
242
+ deactivateWidget(app);
243
+ active = false;
244
+ }
245
+ return await initHooks?.teardown?.(params, extra) ?? {};
246
+ };
247
+ (async () => {
248
+ try {
249
+ await initHooks?.before?.();
250
+ if (cancelled) return;
251
+ try {
252
+ await app.connect();
253
+ } catch (err) {
254
+ if (!(err instanceof Error && err.message.includes("already connected"))) throw err;
255
+ }
256
+ if (cancelled) return;
257
+ activateWidget(app);
258
+ active = true;
259
+ await initHooks?.after?.();
260
+ if (!cancelled) setConnected(true);
261
+ else {
262
+ deactivateWidget(app);
263
+ active = false;
264
+ }
265
+ } catch (err) {
266
+ if (active) {
267
+ deactivateWidget(app);
268
+ active = false;
269
+ }
270
+ if (!cancelled) setError(err instanceof Error ? err : new Error(String(err)));
271
+ }
272
+ })();
273
+ return () => {
274
+ cancelled = true;
275
+ if (active) {
276
+ deactivateWidget(app);
277
+ active = false;
278
+ }
279
+ app.close();
280
+ if (appRef.current === app) appRef.current = null;
281
+ };
282
+ }, []);
283
+ if (error) {
284
+ if (typeof errorUI === "function") return errorUI(error);
285
+ if (errorUI !== void 0) return errorUI;
286
+ return /* @__PURE__ */ jsxs("div", { children: [
287
+ /* @__PURE__ */ jsx("strong", { children: "ERROR:" }),
288
+ " ",
289
+ error.message
290
+ ] });
291
+ }
292
+ if (!connected || appRef.current == null) return fallback ?? /* @__PURE__ */ jsx("div", { children: "Connecting..." });
293
+ return /* @__PURE__ */ jsx(WidgetContext.Provider, {
294
+ value: {
295
+ app: appRef.current,
296
+ tool: toolLifecycle
297
+ },
298
+ children
299
+ });
300
+ }
301
+ function mountWidget(Widget) {
302
+ if (!rootInstance) {
303
+ const element = document.querySelector("#root");
304
+ if (!(element instanceof HTMLElement)) throw new Error("Widget root #root was not found");
305
+ rootInstance = createRoot(element);
306
+ }
307
+ rootInstance.render(/* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsx(Widget, {}) }));
308
+ }
309
+ //#endregion
310
+ export { McpToolCancelledError, McpToolError, Widget, downloadFile, mountWidget, openLink, requestDisplayMode, requestTeardown, sendLog, sendMessage, updateModelContext, useToolResult, useWidget };
311
+
312
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/app.ts","../src/use-tool-result.ts","../src/index.tsx"],"sourcesContent":["import type { App } from \"@modelcontextprotocol/ext-apps\";\n\nimport { getActiveWidget } from \"./widget-context\";\n\nexport function sendMessage(\n ...args: Parameters<App[\"sendMessage\"]>\n): ReturnType<App[\"sendMessage\"]> {\n return getActiveWidget().sendMessage(...args);\n}\n\nexport function sendLog(\n ...args: Parameters<App[\"sendLog\"]>\n): ReturnType<App[\"sendLog\"]> {\n return getActiveWidget().sendLog(...args);\n}\n\nexport function updateModelContext(\n ...args: Parameters<App[\"updateModelContext\"]>\n): ReturnType<App[\"updateModelContext\"]> {\n return getActiveWidget().updateModelContext(...args);\n}\n\nexport function openLink(\n ...args: Parameters<App[\"openLink\"]>\n): ReturnType<App[\"openLink\"]> {\n return getActiveWidget().openLink(...args);\n}\n\nexport function downloadFile(\n ...args: Parameters<App[\"downloadFile\"]>\n): ReturnType<App[\"downloadFile\"]> {\n return getActiveWidget().downloadFile(...args);\n}\n\nexport function requestDisplayMode(\n ...args: Parameters<App[\"requestDisplayMode\"]>\n): ReturnType<App[\"requestDisplayMode\"]> {\n return getActiveWidget().requestDisplayMode(...args);\n}\n\nexport function requestTeardown(\n ...args: Parameters<App[\"requestTeardown\"]>\n): ReturnType<App[\"requestTeardown\"]> {\n return getActiveWidget().requestTeardown(...args);\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\nimport {\n McpToolCancelledError,\n type RawToolResult,\n type ToolCallError,\n type ToolCallResult,\n} from \"./tool-error\";\nimport {\n errorResult,\n getToolResultAdapter,\n type ToolResultAdapter,\n type ToolResultSource,\n} from \"./tool-result-source\";\nimport {\n useConnectedWidgetContext,\n type WidgetToolLifecycle,\n} from \"./widget-context\";\n\nexport type ToolResultStatus = \"pending\" | \"success\" | \"error\";\n\nexport type ToolResultState<Input extends object, Output> = {\n data: Output | undefined;\n error: ToolCallError | undefined;\n rawResult: RawToolResult | undefined;\n status: ToolResultStatus;\n isLoading: boolean;\n isFetching: boolean;\n isSuccess: boolean;\n isError: boolean;\n execute: (input?: Input) => Promise<ToolCallResult<Output>>;\n};\n\ntype ResultSnapshot<Output> = {\n data: Output | undefined;\n error: ToolCallError | undefined;\n rawResult: RawToolResult | undefined;\n status: ToolResultStatus;\n isFetching: boolean;\n};\n\nfunction sourceMismatchError(\n expectedName: string,\n actualName: string | undefined,\n): Error | undefined {\n if (actualName === undefined || actualName === expectedName) {\n return undefined;\n }\n return new Error(\n `useToolResult expected opening tool ${JSON.stringify(expectedName)}, received ${JSON.stringify(actualName)}`,\n );\n}\n\nfunction openingSnapshot<Input extends object, Output>(\n adapter: ToolResultAdapter<Input, Output>,\n lifecycle: WidgetToolLifecycle,\n mismatch: Error | undefined,\n): ResultSnapshot<Output> {\n if (mismatch !== undefined) {\n return {\n data: undefined,\n error: mismatch,\n rawResult: lifecycle.rawResult,\n status: \"error\",\n isFetching: false,\n };\n }\n if (lifecycle.status === \"pending\") {\n return {\n data: undefined,\n error: undefined,\n rawResult: undefined,\n status: \"pending\",\n isFetching: true,\n };\n }\n if (lifecycle.status === \"cancelled\") {\n return {\n data: undefined,\n error: new McpToolCancelledError(\n adapter.name,\n lifecycle.cancellationReason,\n ),\n rawResult: undefined,\n status: \"error\",\n isFetching: false,\n };\n }\n\n const rawResult = lifecycle.rawResult!;\n const callResult = adapter.parse(rawResult);\n return callResult.error === undefined\n ? {\n data: callResult.result,\n error: undefined,\n rawResult,\n status: \"success\",\n isFetching: false,\n }\n : {\n data: undefined,\n error: callResult.error,\n rawResult,\n status: \"error\",\n isFetching: false,\n };\n}\n\nexport function useToolResult<Input extends object, Output>(\n source: ToolResultSource<Input, Output>,\n): ToolResultState<Input, Output> {\n const context = useConnectedWidgetContext(\"useToolResult\");\n const adapter = getToolResultAdapter(source);\n const [hostToolName, setHostToolName] = useState<string | undefined>(\n () => context.app.getHostContext()?.toolInfo?.tool.name,\n );\n const mismatch = useMemo(\n () => sourceMismatchError(adapter.name, hostToolName),\n [adapter.name, hostToolName],\n );\n const [snapshot, setSnapshot] = useState<ResultSnapshot<Output>>(() =>\n openingSnapshot(adapter, context.tool, mismatch),\n );\n const hasExecutedRef = useRef(false);\n const hasExplicitInputRef = useRef(false);\n const latestInputRef = useRef<Input | undefined>(\n context.tool.input as Input | undefined,\n );\n const latestRequestRef = useRef(0);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n latestRequestRef.current += 1;\n };\n }, []);\n\n useEffect(() => {\n const syncHostToolName = () => {\n setHostToolName(context.app.getHostContext()?.toolInfo?.tool.name);\n };\n syncHostToolName();\n context.app.addEventListener(\"hostcontextchanged\", syncHostToolName);\n return () => {\n context.app.removeEventListener(\"hostcontextchanged\", syncHostToolName);\n };\n }, [context.app]);\n\n useEffect(() => {\n if (!hasExplicitInputRef.current && context.tool.inputReceived) {\n latestInputRef.current = context.tool.input as Input | undefined;\n }\n }, [context.tool.input, context.tool.inputReceived]);\n\n useEffect(() => {\n if (!hasExecutedRef.current) {\n setSnapshot(openingSnapshot(adapter, context.tool, mismatch));\n }\n }, [adapter, context.tool, mismatch]);\n\n const execute = useCallback(\n async function execute(input?: Input): Promise<ToolCallResult<Output>> {\n hasExecutedRef.current = true;\n if (arguments.length > 0) {\n hasExplicitInputRef.current = true;\n latestInputRef.current = input;\n }\n\n const request = ++latestRequestRef.current;\n if (mismatch !== undefined) {\n setSnapshot((current) => ({\n ...current,\n error: mismatch,\n status: \"error\",\n isFetching: false,\n }));\n return errorResult(mismatch);\n }\n\n setSnapshot((current) => ({\n ...current,\n error: undefined,\n status: current.data === undefined ? \"pending\" : \"success\",\n isFetching: true,\n }));\n const execution = await adapter.execute(\n latestInputRef.current,\n context.app,\n );\n if (mountedRef.current && request === latestRequestRef.current) {\n setSnapshot((current) =>\n execution.callResult.error === undefined\n ? {\n data: execution.callResult.result,\n error: undefined,\n rawResult: execution.rawResult ?? current.rawResult,\n status: \"success\",\n isFetching: false,\n }\n : {\n data: current.data,\n error: execution.callResult.error,\n rawResult: execution.rawResult ?? current.rawResult,\n status: \"error\",\n isFetching: false,\n },\n );\n }\n return execution.callResult;\n },\n [adapter, context.app, mismatch],\n );\n\n return {\n data: snapshot.data,\n error: snapshot.error,\n rawResult: snapshot.rawResult,\n status: snapshot.status,\n isLoading: snapshot.isFetching && snapshot.data === undefined,\n isFetching: snapshot.isFetching,\n isSuccess: snapshot.status === \"success\",\n isError: snapshot.status === \"error\",\n execute,\n };\n}\n","import {\n StrictMode,\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport { createRoot, type Root } from \"react-dom/client\";\nimport {\n App,\n type AppEventMap,\n type AppOptions,\n type McpUiAppCapabilities,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n WidgetContext,\n activateWidget,\n deactivateWidget,\n useWidget,\n type WidgetToolLifecycle,\n} from \"./widget-context\";\n\nexport {\n downloadFile,\n openLink,\n requestDisplayMode,\n requestTeardown,\n sendLog,\n sendMessage,\n updateModelContext,\n} from \"./app\";\n\nexport {\n McpToolCancelledError,\n McpToolError,\n type McpToolErrorResult,\n type RawToolResult,\n type ToolCallError,\n type ToolCallResult,\n} from \"./tool-error\";\n\nexport {\n useToolResult,\n type ToolResultState,\n type ToolResultStatus,\n} from \"./use-tool-result\";\n\nexport { useWidget };\n\nexport type WidgetMetadata = {\n name: string;\n version: string;\n title?: string;\n capabilities?: McpUiAppCapabilities;\n} & Pick<AppOptions, \"autoResize\" | \"strict\">;\n\nexport type WidgetHooks = {\n before?: () => void | Promise<void>;\n after?: () => void | Promise<void>;\n error?: (error: Error) => void;\n toolInput?: (params: AppEventMap[\"toolinput\"]) => void;\n toolInputPartial?: (params: AppEventMap[\"toolinputpartial\"]) => void;\n toolResult?: (params: AppEventMap[\"toolresult\"]) => void;\n toolCancelled?: (params: AppEventMap[\"toolcancelled\"]) => void;\n hostContextChanged?: (params: AppEventMap[\"hostcontextchanged\"]) => void;\n teardown?: NonNullable<App[\"onteardown\"]>;\n};\n\nexport type WidgetProps = {\n metadata: WidgetMetadata;\n children: ReactNode;\n hooks?: WidgetHooks;\n fallback?: ReactNode;\n error?: ReactNode | ((error: Error) => ReactNode);\n};\n\nfunction applyHooks(app: App, hooks: WidgetHooks | undefined): void {\n app.onerror = hooks?.error ?? ((error) => console.error(error));\n if (!hooks) {\n return;\n }\n if (hooks.toolInput) {\n app.addEventListener(\"toolinput\", hooks.toolInput);\n }\n if (hooks.toolInputPartial) {\n app.addEventListener(\"toolinputpartial\", hooks.toolInputPartial);\n }\n if (hooks.toolResult) {\n app.addEventListener(\"toolresult\", hooks.toolResult);\n }\n if (hooks.toolCancelled) {\n app.addEventListener(\"toolcancelled\", hooks.toolCancelled);\n }\n if (hooks.hostContextChanged) {\n app.addEventListener(\"hostcontextchanged\", hooks.hostContextChanged);\n }\n}\n\nfunction initialToolLifecycle(): WidgetToolLifecycle {\n return {\n input: undefined,\n inputReceived: false,\n rawResult: undefined,\n cancellationReason: undefined,\n status: \"pending\",\n version: 0,\n };\n}\n\nlet rootInstance: Root | null = null;\n\nexport function Widget({\n metadata,\n children,\n hooks,\n fallback,\n error: errorUI,\n}: WidgetProps) {\n const [connected, setConnected] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [toolLifecycle, setToolLifecycle] = useState(initialToolLifecycle);\n const appRef = useRef<App | null>(null);\n const initRef = useRef<{ metadata: WidgetMetadata; hooks: WidgetHooks | undefined } | null>(\n null,\n );\n if (initRef.current == null) {\n initRef.current = { metadata, hooks };\n }\n\n useEffect(() => {\n let cancelled = false;\n let active = false;\n const { metadata: meta, hooks: initHooks } = initRef.current!;\n const { capabilities, autoResize, strict, name, version, title } = meta;\n const options: AppOptions = {};\n if (autoResize !== undefined) {\n options.autoResize = autoResize;\n }\n if (strict !== undefined) {\n options.strict = strict;\n }\n const app = new App(\n title === undefined ? { name, version } : { name, version, title },\n capabilities ?? {},\n options,\n );\n appRef.current = app;\n setToolLifecycle(initialToolLifecycle());\n app.addEventListener(\"toolinput\", (params) => {\n if (!cancelled) {\n setToolLifecycle((current) => ({\n ...current,\n input: params.arguments,\n inputReceived: true,\n }));\n }\n });\n app.addEventListener(\"toolresult\", (params) => {\n if (!cancelled) {\n setToolLifecycle((current) => ({\n ...current,\n rawResult: params,\n cancellationReason: undefined,\n status: \"result\",\n version: current.version + 1,\n }));\n }\n });\n app.addEventListener(\"toolcancelled\", (params) => {\n if (!cancelled) {\n setToolLifecycle((current) => ({\n ...current,\n rawResult: undefined,\n cancellationReason: params.reason,\n status: \"cancelled\",\n version: current.version + 1,\n }));\n }\n });\n applyHooks(app, initHooks);\n app.onteardown = async (params, extra) => {\n if (active) {\n deactivateWidget(app);\n active = false;\n }\n return (await initHooks?.teardown?.(params, extra)) ?? {};\n };\n\n void (async () => {\n try {\n await initHooks?.before?.();\n if (cancelled) {\n return;\n }\n try {\n await app.connect();\n } catch (err: unknown) {\n if (!(err instanceof Error && err.message.includes(\"already connected\"))) {\n throw err;\n }\n }\n if (cancelled) {\n return;\n }\n activateWidget(app);\n active = true;\n await initHooks?.after?.();\n if (!cancelled) {\n setConnected(true);\n } else {\n deactivateWidget(app);\n active = false;\n }\n } catch (err: unknown) {\n if (active) {\n deactivateWidget(app);\n active = false;\n }\n if (!cancelled) {\n setError(err instanceof Error ? err : new Error(String(err)));\n }\n }\n })();\n\n return () => {\n cancelled = true;\n if (active) {\n deactivateWidget(app);\n active = false;\n }\n void app.close();\n if (appRef.current === app) {\n appRef.current = null;\n }\n };\n }, []);\n\n if (error) {\n if (typeof errorUI === \"function\") return errorUI(error);\n if (errorUI !== undefined) return errorUI;\n return (\n <div>\n <strong>ERROR:</strong> {error.message}\n </div>\n );\n }\n if (!connected || appRef.current == null) {\n return fallback ?? <div>Connecting...</div>;\n }\n\n return (\n <WidgetContext.Provider\n value={{ app: appRef.current, tool: toolLifecycle }}\n >\n {children}\n </WidgetContext.Provider>\n );\n}\n\nexport function mountWidget(Widget: ComponentType): void {\n if (!rootInstance) {\n const element = document.querySelector(\"#root\");\n if (!(element instanceof HTMLElement)) {\n throw new Error(\"Widget root #root was not found\");\n }\n rootInstance = createRoot(element);\n }\n\n rootInstance.render(\n <StrictMode>\n <Widget />\n </StrictMode>,\n );\n}\n"],"mappings":";;;;;;AAIA,SAAgB,YACd,GAAG,MAC6B;CAChC,OAAO,gBAAgB,CAAC,CAAC,YAAY,GAAG,IAAI;AAC9C;AAEA,SAAgB,QACd,GAAG,MACyB;CAC5B,OAAO,gBAAgB,CAAC,CAAC,QAAQ,GAAG,IAAI;AAC1C;AAEA,SAAgB,mBACd,GAAG,MACoC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CAEL,IAAI,OAAO;EACT,IAAI,OAAO,YAAY,YAAY,OAAO,QAAQ,KAAK;EACvD,IAAI,YAAY,KAAA,GAAW,OAAO;EAClC,OACE,qBAAC,OAAD,EAAA,UAAA;GACE,oBAAC,UAAD,EAAA,UAAQ,SAAc,CAAA;GAAC;GAAE,MAAM;EAC5B,EAAA,CAAA;CAET;CACA,IAAI,CAAC,aAAa,OAAO,WAAW,MAClC,OAAO,YAAY,oBAAC,OAAD,EAAA,UAAK,gBAAkB,CAAA;CAG5C,OACE,oBAAC,cAAc,UAAf;EACE,OAAO;GAAE,KAAK,OAAO;GAAS,MAAM;EAAc;EAEjD;CACqB,CAAA;AAE5B;AAEA,SAAgB,YAAY,QAA6B;CACvD,IAAI,CAAC,cAAc;EACjB,MAAM,UAAU,SAAS,cAAc,OAAO;EAC9C,IAAI,EAAE,mBAAmB,cACvB,MAAM,IAAI,MAAM,iCAAiC;EAEnD,eAAe,WAAW,OAAO;CACnC;CAEA,aAAa,OACX,oBAAC,YAAD,EAAA,UACE,oBAAC,QAAD,CAAS,CAAA,EACC,CAAA,CACd;AACF"}
@@ -0,0 +1,12 @@
1
+ import { a as RawToolResult, s as ToolCallResult, t as ToolResultSource } from "./tool-result-source-niHoRYxM.js";
2
+ import { z } from "zod";
3
+ import { App } from "@modelcontextprotocol/ext-apps";
4
+ //#region src/internal.d.ts
5
+ type GeneratedToolCall<Input extends object, Output> = {} extends Input ? (input?: Input, app?: App) => Promise<ToolCallResult<Output>> : (input: Input, app?: App) => Promise<ToolCallResult<Output>>;
6
+ type GeneratedTool<Input extends object, Output> = GeneratedToolCall<Input, Output> & ToolResultSource<Input, Output>;
7
+ type OutputSchema = Parameters<typeof z.fromJSONSchema>[0];
8
+ declare function createGeneratedTool<Input extends object, Output>(name: string, outputSchema: OutputSchema): GeneratedTool<Input, Output>;
9
+ declare function createGeneratedRawTool<Input extends object>(name: string): GeneratedTool<Input, RawToolResult>;
10
+ //#endregion
11
+ export { createGeneratedRawTool, createGeneratedTool };
12
+ //# sourceMappingURL=internal.d.ts.map
@@ -0,0 +1,37 @@
1
+ import { a as normalizeToolCallError, d as getActiveWidget, n as createToolResultAdapter, r as errorResult, t as TOOL_RESULT_SOURCE } from "./tool-result-source-DTFIKHfH.js";
2
+ import { z } from "zod";
3
+ //#region src/internal.ts
4
+ function createGeneratedToolCaller(name, success) {
5
+ const adapter = createToolResultAdapter(name, success);
6
+ const caller = async (input, explicitApp) => {
7
+ try {
8
+ const app = explicitApp ?? getActiveWidget();
9
+ return (await adapter.execute(input, app)).callResult;
10
+ } catch (cause) {
11
+ return errorResult(normalizeToolCallError(cause));
12
+ }
13
+ };
14
+ Object.defineProperty(caller, TOOL_RESULT_SOURCE, { value: adapter });
15
+ return caller;
16
+ }
17
+ function createGeneratedTool(name, outputSchema) {
18
+ const schema = z.fromJSONSchema(outputSchema);
19
+ return createGeneratedToolCaller(name, (response) => {
20
+ const parsed = schema.safeParse(response.structuredContent);
21
+ if (!parsed.success) return errorResult(parsed.error);
22
+ return {
23
+ result: parsed.data,
24
+ error: void 0
25
+ };
26
+ });
27
+ }
28
+ function createGeneratedRawTool(name) {
29
+ return createGeneratedToolCaller(name, (response) => ({
30
+ result: response,
31
+ error: void 0
32
+ }));
33
+ }
34
+ //#endregion
35
+ export { createGeneratedRawTool, createGeneratedTool };
36
+
37
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import type { App } from \"@modelcontextprotocol/ext-apps\";\nimport { z } from \"zod\";\n\nimport { getActiveWidget } from \"./widget-context\";\nimport {\n type RawToolResult,\n type ToolCallResult,\n} from \"./tool-error\";\nimport {\n TOOL_RESULT_SOURCE,\n createToolResultAdapter,\n errorResult,\n normalizeToolCallError,\n type ToolResultSource,\n} from \"./tool-result-source\";\n\ntype GeneratedToolCall<Input extends object, Output> = {} extends Input\n ? (input?: Input, app?: App) => Promise<ToolCallResult<Output>>\n : (input: Input, app?: App) => Promise<ToolCallResult<Output>>;\n\ntype GeneratedTool<Input extends object, Output> = GeneratedToolCall<\n Input,\n Output\n> &\n ToolResultSource<Input, Output>;\n\ntype OutputSchema = Parameters<typeof z.fromJSONSchema>[0];\n\nfunction createGeneratedToolCaller<Input extends object, Output>(\n name: string,\n success: (response: RawToolResult) => ToolCallResult<Output>,\n): GeneratedTool<Input, Output> {\n const adapter = createToolResultAdapter<Input, Output>(name, success);\n const caller = async (\n input?: Input,\n explicitApp?: App,\n ): Promise<ToolCallResult<Output>> => {\n try {\n const app = explicitApp ?? getActiveWidget();\n return (await adapter.execute(input, app)).callResult;\n } catch (cause: unknown) {\n return errorResult(normalizeToolCallError(cause));\n }\n };\n Object.defineProperty(caller, TOOL_RESULT_SOURCE, { value: adapter });\n return caller as GeneratedTool<Input, Output>;\n}\n\nexport function createGeneratedTool<Input extends object, Output>(\n name: string,\n outputSchema: OutputSchema,\n): GeneratedTool<Input, Output> {\n const schema = z.fromJSONSchema(outputSchema) as z.ZodType<Output>;\n\n return createGeneratedToolCaller(name, (response) => {\n const parsed = schema.safeParse(response.structuredContent);\n if (!parsed.success) {\n return errorResult(parsed.error);\n }\n return { result: parsed.data, error: undefined };\n });\n}\n\nexport function createGeneratedRawTool<Input extends object>(\n name: string,\n): GeneratedTool<Input, RawToolResult> {\n return createGeneratedToolCaller(name, (response) => ({\n result: response,\n error: undefined,\n }));\n}\n"],"mappings":";;;AA4BA,SAAS,0BACP,MACA,SAC8B;CAC9B,MAAM,UAAU,wBAAuC,MAAM,OAAO;CACpE,MAAM,SAAS,OACb,OACA,gBACoC;EACpC,IAAI;GACF,MAAM,MAAM,eAAe,gBAAgB;GAC3C,QAAQ,MAAM,QAAQ,QAAQ,OAAO,GAAG,EAAA,CAAG;EAC7C,SAAS,OAAgB;GACvB,OAAO,YAAY,uBAAuB,KAAK,CAAC;EAClD;CACF;CACA,OAAO,eAAe,QAAQ,oBAAoB,EAAE,OAAO,QAAQ,CAAC;CACpE,OAAO;AACT;AAEA,SAAgB,oBACd,MACA,cAC8B;CAC9B,MAAM,SAAS,EAAE,eAAe,YAAY;CAE5C,OAAO,0BAA0B,OAAO,aAAa;EACnD,MAAM,SAAS,OAAO,UAAU,SAAS,iBAAiB;EAC1D,IAAI,CAAC,OAAO,SACV,OAAO,YAAY,OAAO,KAAK;EAEjC,OAAO;GAAE,QAAQ,OAAO;GAAM,OAAO,KAAA;EAAU;CACjD,CAAC;AACH;AAEA,SAAgB,uBACd,MACqC;CACrC,OAAO,0BAA0B,OAAO,cAAc;EACpD,QAAQ;EACR,OAAO,KAAA;CACT,EAAE;AACJ"}