@belgie/mcp 0.1.0 → 0.32.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.
@@ -1 +0,0 @@
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,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,oBAAoB,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,W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M,WAAW,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"}
package/dist/codegen.d.ts DELETED
@@ -1,11 +0,0 @@
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
package/dist/codegen.js DELETED
@@ -1,2 +0,0 @@
1
- import { t as generateToolTypes } from "./codegen-DnMS1wg_.js";
2
- export { generateToolTypes };
package/dist/index.d.ts DELETED
@@ -1,60 +0,0 @@
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
@@ -1,12 +0,0 @@
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
package/dist/internal.js DELETED
@@ -1,37 +0,0 @@
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
@@ -1 +0,0 @@
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"}
@@ -1,99 +0,0 @@
1
- import { createContext, useContext } from "react";
2
- //#region src/widget-context.ts
3
- const WidgetContext = createContext(null);
4
- let activeWidget = null;
5
- function activateWidget(app) {
6
- if (activeWidget !== null && activeWidget !== app) throw new Error("Only one connected <Widget> can be active at a time");
7
- activeWidget = app;
8
- }
9
- function deactivateWidget(app) {
10
- if (activeWidget === app) activeWidget = null;
11
- }
12
- function getActiveWidget() {
13
- if (activeWidget === null) throw new Error("Tool calls require an active connected <Widget>");
14
- return activeWidget;
15
- }
16
- function useWidgetContext() {
17
- return useContext(WidgetContext);
18
- }
19
- function useConnectedWidgetContext(name) {
20
- const context = useWidgetContext();
21
- if (context == null) throw new Error(`${name} must be used within a connected <Widget>`);
22
- return context;
23
- }
24
- function useWidget() {
25
- return useConnectedWidgetContext("useWidget").app;
26
- }
27
- //#endregion
28
- //#region src/tool-error.ts
29
- function mcpToolErrorMessage(toolName, result) {
30
- return result.content.map((content) => content.type === "text" ? content.text : "").filter(Boolean).join("\n") || `MCP tool ${JSON.stringify(toolName)} returned an error`;
31
- }
32
- var McpToolError = class extends Error {
33
- toolName;
34
- result;
35
- constructor(toolName, result) {
36
- super(mcpToolErrorMessage(toolName, result), { cause: result });
37
- this.name = "McpToolError";
38
- this.toolName = toolName;
39
- this.result = result;
40
- }
41
- };
42
- var McpToolCancelledError = class extends Error {
43
- toolName;
44
- reason;
45
- constructor(toolName, reason) {
46
- super(reason === void 0 ? `MCP tool ${JSON.stringify(toolName)} was cancelled` : `MCP tool ${JSON.stringify(toolName)} was cancelled: ${reason}`);
47
- this.name = "McpToolCancelledError";
48
- this.toolName = toolName;
49
- this.reason = reason;
50
- }
51
- };
52
- //#endregion
53
- //#region src/tool-result-source.ts
54
- const TOOL_RESULT_SOURCE = Symbol("belgie.tool-result-source");
55
- function errorResult(error) {
56
- return {
57
- result: void 0,
58
- error
59
- };
60
- }
61
- function normalizeToolCallError(cause) {
62
- return cause instanceof Error ? cause : new Error(String(cause));
63
- }
64
- function createToolResultAdapter(name, success) {
65
- const parse = (response) => {
66
- if (response.isError) return errorResult(new McpToolError(name, response));
67
- return success(response);
68
- };
69
- return {
70
- name,
71
- parse,
72
- async execute(input, app) {
73
- try {
74
- const rawResult = await app.callServerTool({
75
- name,
76
- ...input === void 0 ? {} : { arguments: input }
77
- });
78
- return {
79
- callResult: parse(rawResult),
80
- rawResult
81
- };
82
- } catch (cause) {
83
- return {
84
- callResult: errorResult(normalizeToolCallError(cause)),
85
- rawResult: void 0
86
- };
87
- }
88
- }
89
- };
90
- }
91
- function getToolResultAdapter(source) {
92
- const adapter = source[TOOL_RESULT_SOURCE];
93
- if (adapter === void 0) throw new Error("useToolResult requires a generated MCP tool caller");
94
- return adapter;
95
- }
96
- //#endregion
97
- export { normalizeToolCallError as a, WidgetContext as c, getActiveWidget as d, useConnectedWidgetContext as f, getToolResultAdapter as i, activateWidget as l, createToolResultAdapter as n, McpToolCancelledError as o, useWidget as p, errorResult as r, McpToolError as s, TOOL_RESULT_SOURCE as t, deactivateWidget as u };
98
-
99
- //# sourceMappingURL=tool-result-source-DTFIKHfH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tool-result-source-DTFIKHfH.js","names":[],"sources":["../src/widget-context.ts","../src/tool-error.ts","../src/tool-result-source.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\n\nimport type { App } from \"@modelcontextprotocol/ext-apps\";\nimport type { RawToolResult } from \"./tool-error\";\n\nexport type WidgetToolLifecycle = {\n input: Record<string, unknown> | undefined;\n inputReceived: boolean;\n rawResult: RawToolResult | undefined;\n cancellationReason: string | undefined;\n status: \"pending\" | \"result\" | \"cancelled\";\n version: number;\n};\n\nexport type WidgetContextValue = {\n app: App;\n tool: WidgetToolLifecycle;\n};\n\nexport const WidgetContext = createContext<WidgetContextValue | null>(null);\n\nlet activeWidget: App | null = null;\n\nexport function activateWidget(app: App): void {\n if (activeWidget !== null && activeWidget !== app) {\n throw new Error(\"Only one connected <Widget> can be active at a time\");\n }\n activeWidget = app;\n}\n\nexport function deactivateWidget(app: App): void {\n if (activeWidget === app) {\n activeWidget = null;\n }\n}\n\nexport function getActiveWidget(): App {\n if (activeWidget === null) {\n throw new Error(\"Tool calls require an active connected <Widget>\");\n }\n return activeWidget;\n}\n\nexport function useWidgetContext(): WidgetContextValue | null {\n return useContext(WidgetContext);\n}\n\nexport function useConnectedWidgetContext(name: string): WidgetContextValue {\n const context = useWidgetContext();\n if (context == null) {\n throw new Error(`${name} must be used within a connected <Widget>`);\n }\n return context;\n}\n\nexport function useWidget(): App {\n return useConnectedWidgetContext(\"useWidget\").app;\n}\n","import type { App } from \"@modelcontextprotocol/ext-apps\";\n\nexport type RawToolResult = Awaited<ReturnType<App[\"callServerTool\"]>>;\n\nexport type McpToolErrorResult = RawToolResult & { isError: true };\n\nfunction mcpToolErrorMessage(\n toolName: string,\n result: McpToolErrorResult,\n): string {\n return (\n result.content\n .map((content) => (content.type === \"text\" ? content.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\") || `MCP tool ${JSON.stringify(toolName)} returned an error`\n );\n}\n\nexport class McpToolError extends Error {\n readonly toolName: string;\n readonly result: McpToolErrorResult;\n\n constructor(toolName: string, result: McpToolErrorResult) {\n super(mcpToolErrorMessage(toolName, result), { cause: result });\n this.name = \"McpToolError\";\n this.toolName = toolName;\n this.result = result;\n }\n}\n\nexport class McpToolCancelledError extends Error {\n readonly toolName: string;\n readonly reason: string | undefined;\n\n constructor(toolName: string, reason?: string) {\n super(\n reason === undefined\n ? `MCP tool ${JSON.stringify(toolName)} was cancelled`\n : `MCP tool ${JSON.stringify(toolName)} was cancelled: ${reason}`,\n );\n this.name = \"McpToolCancelledError\";\n this.toolName = toolName;\n this.reason = reason;\n }\n}\n\nexport type ToolCallError = Error;\n\nexport type ToolCallResult<Output> =\n | { result: Output; error: undefined }\n | { result: undefined; error: ToolCallError };\n","import type { App } from \"@modelcontextprotocol/ext-apps\";\n\nimport {\n McpToolError,\n type McpToolErrorResult,\n type RawToolResult,\n type ToolCallError,\n type ToolCallResult,\n} from \"./tool-error\";\n\nexport const TOOL_RESULT_SOURCE: unique symbol = Symbol(\n \"belgie.tool-result-source\",\n);\n\nexport type ToolResultExecution<Output> = {\n callResult: ToolCallResult<Output>;\n rawResult: RawToolResult | undefined;\n};\n\nexport type ToolResultAdapter<Input extends object, Output> = {\n name: string;\n execute: (\n input: Input | undefined,\n app: App,\n ) => Promise<ToolResultExecution<Output>>;\n parse: (response: RawToolResult) => ToolCallResult<Output>;\n};\n\nexport type ToolResultSource<Input extends object, Output> = {\n readonly [TOOL_RESULT_SOURCE]: ToolResultAdapter<Input, Output>;\n};\n\nexport function errorResult(error: ToolCallError): ToolCallResult<never> {\n return { result: undefined, error };\n}\n\nexport function normalizeToolCallError(cause: unknown): ToolCallError {\n return cause instanceof Error ? cause : new Error(String(cause));\n}\n\nexport function createToolResultAdapter<Input extends object, Output>(\n name: string,\n success: (response: RawToolResult) => ToolCallResult<Output>,\n): ToolResultAdapter<Input, Output> {\n const parse = (response: RawToolResult): ToolCallResult<Output> => {\n if (response.isError) {\n return errorResult(\n new McpToolError(name, response as McpToolErrorResult),\n );\n }\n return success(response);\n };\n\n return {\n name,\n parse,\n async execute(input, app) {\n try {\n const rawResult = await app.callServerTool({\n name,\n ...(input === undefined\n ? {}\n : { arguments: input as Record<string, unknown> }),\n });\n return { callResult: parse(rawResult), rawResult };\n } catch (cause: unknown) {\n return {\n callResult: errorResult(normalizeToolCallError(cause)),\n rawResult: undefined,\n };\n }\n },\n };\n}\n\nexport function getToolResultAdapter<Input extends object, Output>(\n source: ToolResultSource<Input, Output>,\n): ToolResultAdapter<Input, Output> {\n const adapter = source[TOOL_RESULT_SOURCE];\n if (adapter === undefined) {\n throw new Error(\"useToolResult requires a generated MCP tool caller\");\n }\n return adapter;\n}\n"],"mappings":";;AAmBA,MAAa,gBAAgB,cAAyC,IAAI;AAE1E,IAAI,eAA2B;AAE/B,SAAgB,eAAe,KAAgB;CAC7C,IAAI,iBAAiB,QAAQ,iBAAiB,KAC5C,MAAM,IAAI,MAAM,qDAAqD;CAEvE,eAAe;AACjB;AAEA,SAAgB,iBAAiB,KAAgB;CAC/C,IAAI,iBAAiB,KACnB,eAAe;AAEnB;AAEA,SAAgB,kBAAuB;CACrC,IAAI,iBAAiB,MACnB,MAAM,IAAI,MAAM,iDAAiD;CAEnE,OAAO;AACT;AAEA,SAAgB,mBAA8C;CAC5D,OAAO,WAAW,aAAa;AACjC;AAEA,SAAgB,0BAA0B,MAAkC;CAC1E,MAAM,UAAU,iBAAiB;CACjC,IAAI,WAAW,MACb,MAAM,IAAI,MAAM,GAAG,KAAK,0CAA0C;CAEpE,OAAO;AACT;AAEA,SAAgB,YAAiB;CAC/B,OAAO,0BAA0B,WAAW,CAAC,CAAC;AAChD;;;ACnDA,SAAS,oBACP,UACA,QACQ;CACR,OACE,OAAO,QACJ,KAAK,YAAa,QAAQ,SAAS,SAAS,QAAQ,OAAO,EAAG,CAAC,CAC/D,OAAO,OAAO,CAAC,CACf,KAAK,IAAI,KAAK,YAAY,KAAK,UAAU,QAAQ,EAAE;AAE1D;AAEA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CAEA,YAAY,UAAkB,QAA4B;EACxD,MAAM,oBAAoB,UAAU,MAAM,GAAG,EAAE,OAAO,OAAO,CAAC;EAC9D,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,SAAS;CAChB;AACF;AAEA,IAAa,wBAAb,cAA2C,MAAM;CAC/C;CACA;CAEA,YAAY,UAAkB,QAAiB;EAC7C,MACE,WAAW,KAAA,IACP,YAAY,KAAK,UAAU,QAAQ,EAAE,kBACrC,YAAY,KAAK,UAAU,QAAQ,EAAE,kBAAkB,QAC7D;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,SAAS;CAChB;AACF;;;AClCA,MAAa,qBAAoC,OAC/C,2BACF;AAoBA,SAAgB,YAAY,OAA6C;CACvE,OAAO;EAAE,QAAQ,KAAA;EAAW;CAAM;AACpC;AAEA,SAAgB,uBAAuB,OAA+B;CACpE,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAgB,wBACd,MACA,SACkC;CAClC,MAAM,SAAS,aAAoD;EACjE,IAAI,SAAS,SACX,OAAO,YACL,IAAI,aAAa,MAAM,QAA8B,CACvD;EAEF,OAAO,QAAQ,QAAQ;CACzB;CAEA,OAAO;EACL;EACA;EACA,MAAM,QAAQ,OAAO,KAAK;GACxB,IAAI;IACF,MAAM,YAAY,MAAM,IAAI,eAAe;KACzC;KACA,GAAI,UAAU,KAAA,IACV,CAAC,IACD,EAAE,WAAW,MAAiC;IACpD,CAAC;IACD,OAAO;KAAE,YAAY,MAAM,SAAS;KAAG;IAAU;GACnD,SAAS,OAAgB;IACvB,OAAO;KACL,YAAY,YAAY,uBAAuB,KAAK,CAAC;KACrD,WAAW,KAAA;IACb;GACF;EACF;CACF;AACF;AAEA,SAAgB,qBACd,QACkC;CAClC,MAAM,UAAU,OAAO;CACvB,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,oDAAoD;CAEtE,OAAO;AACT"}
@@ -1,42 +0,0 @@
1
- import { App } from "@modelcontextprotocol/ext-apps";
2
- //#region src/tool-error.d.ts
3
- type RawToolResult = Awaited<ReturnType<App["callServerTool"]>>;
4
- type McpToolErrorResult = RawToolResult & {
5
- isError: true;
6
- };
7
- declare class McpToolError extends Error {
8
- readonly toolName: string;
9
- readonly result: McpToolErrorResult;
10
- constructor(toolName: string, result: McpToolErrorResult);
11
- }
12
- declare class McpToolCancelledError extends Error {
13
- readonly toolName: string;
14
- readonly reason: string | undefined;
15
- constructor(toolName: string, reason?: string);
16
- }
17
- type ToolCallError = Error;
18
- type ToolCallResult<Output> = {
19
- result: Output;
20
- error: undefined;
21
- } | {
22
- result: undefined;
23
- error: ToolCallError;
24
- };
25
- //#endregion
26
- //#region src/tool-result-source.d.ts
27
- declare const TOOL_RESULT_SOURCE: unique symbol;
28
- type ToolResultExecution<Output> = {
29
- callResult: ToolCallResult<Output>;
30
- rawResult: RawToolResult | undefined;
31
- };
32
- type ToolResultAdapter<Input extends object, Output> = {
33
- name: string;
34
- execute: (input: Input | undefined, app: App) => Promise<ToolResultExecution<Output>>;
35
- parse: (response: RawToolResult) => ToolCallResult<Output>;
36
- };
37
- type ToolResultSource<Input extends object, Output> = {
38
- readonly [TOOL_RESULT_SOURCE]: ToolResultAdapter<Input, Output>;
39
- };
40
- //#endregion
41
- export { RawToolResult as a, McpToolErrorResult as i, McpToolCancelledError as n, ToolCallError as o, McpToolError as r, ToolCallResult as s, ToolResultSource as t };
42
- //# sourceMappingURL=tool-result-source-niHoRYxM.d.ts.map
package/dist/vite.d.ts DELETED
@@ -1,9 +0,0 @@
1
- import { Plugin } from "vite";
2
- //#region src/vite.d.ts
3
- type BelgiePluginOptions = {
4
- srcDir?: string;
5
- };
6
- declare function belgie(options?: BelgiePluginOptions): Plugin;
7
- //#endregion
8
- export { BelgiePluginOptions, belgie };
9
- //# sourceMappingURL=vite.d.ts.map