@mcp-apps-kit/core
Advanced tools
+1
-1
| { | ||
| "name": "@mcp-apps-kit/core", | ||
| "version": "0.2.3", | ||
| "version": "0.2.4", | ||
| "description": "Server-side framework for building MCP applications", | ||
@@ -5,0 +5,0 @@ "type": "module", |
+190
-267
@@ -5,9 +5,42 @@ # @mcp-apps-kit/core | ||
| Server-side TypeScript framework for building interactive MCP apps that can run on both: | ||
| Server-side framework for building MCP applications. | ||
| - **Claude Desktop (MCP Apps)** | ||
| - **ChatGPT (OpenAI Apps SDK)** | ||
| MCP AppsKit Core is the server runtime for defining tools, validating inputs and outputs with Zod, and binding UI resources. It targets both MCP Apps (Claude Desktop) and ChatGPT (OpenAI Apps SDK) from the same definitions. | ||
| It provides a single `createApp()` API to define tools, validate inputs/outputs with Zod v4, and attach UI resources to tool responses. | ||
| ## Table of Contents | ||
| - [Background](#background) | ||
| - [Features](#features) | ||
| - [Compatibility](#compatibility) | ||
| - [Install](#install) | ||
| - [Usage](#usage) | ||
| - [Type-Safe Tool Definitions](#type-safe-tool-definitions) | ||
| - [Plugins, Middleware & Events](#plugins-middleware--events) | ||
| - [Debug Logging](#debug-logging) | ||
| - [OAuth 2.1 Authentication](#oauth-21-authentication) | ||
| - [OpenAI Domain Verification](#openai-domain-verification) | ||
| - [Examples](#examples) | ||
| - [API](#api) | ||
| - [Contributing](#contributing) | ||
| - [License](#license) | ||
| ## Background | ||
| Interactive MCP apps often need to support multiple hosts with slightly different APIs and metadata rules. Core provides a single server-side API for tools, metadata, and UI resources so you can support MCP Apps and ChatGPT Apps without parallel codebases. | ||
| ## Features | ||
| - Single `createApp()` entry point for tools and UI definitions | ||
| - Zod-powered validation with strong TypeScript inference | ||
| - Unified metadata for MCP Apps and ChatGPT Apps | ||
| - OAuth 2.1 bearer token validation with JWKS discovery | ||
| - Plugins, middleware, and events for cross-cutting concerns | ||
| - Optional debug logging tool for client-to-server logs | ||
| ## Compatibility | ||
| - Node.js: `>= 18` | ||
| - Zod: `^4.0.0` (peer dependency) | ||
| - MCP SDK: uses `@modelcontextprotocol/sdk` | ||
| ## Install | ||
@@ -19,9 +52,6 @@ | ||
| - Node.js: `>=18` | ||
| - Zod: `^4.0.0` | ||
| ## Usage | ||
| ## Quick start | ||
| ### Quick start | ||
| Create an app with one tool using the `defineTool` helper for full type safety: | ||
| ```ts | ||
@@ -43,3 +73,2 @@ import { createApp, defineTool } from "@mcp-apps-kit/core"; | ||
| handler: async (input) => { | ||
| // input.name is fully typed - no assertion needed! | ||
| return { message: `Hello, ${input.name}!` }; | ||
@@ -54,5 +83,36 @@ }, | ||
| ### Attach UI to tool outputs | ||
| Tools can reference a UI resource by ID. Return UI-only payloads in `_meta`. | ||
| ```ts | ||
| const app = createApp({ | ||
| name: "restaurant-finder", | ||
| version: "1.0.0", | ||
| tools: { | ||
| search_restaurants: { | ||
| description: "Search for restaurants by location", | ||
| input: z.object({ location: z.string() }), | ||
| output: z.object({ count: z.number() }), | ||
| handler: async ({ location }) => { | ||
| const restaurants = await fetchRestaurants(location); | ||
| return { | ||
| count: restaurants.length, | ||
| _meta: { restaurants }, | ||
| }; | ||
| }, | ||
| ui: "restaurant-list", | ||
| }, | ||
| }, | ||
| ui: { | ||
| "restaurant-list": { | ||
| html: "./dist/widget.html", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
| ## Type-Safe Tool Definitions | ||
| ### The `defineTool` Helper | ||
| ### The `defineTool` helper | ||
@@ -71,3 +131,2 @@ Use `defineTool` to get automatic type inference in your handlers: | ||
| handler: async (input) => { | ||
| // ✅ input.query and input.maxResults are fully typed! | ||
| return { results: await search(input.query, input.maxResults) }; | ||
@@ -79,12 +138,9 @@ }, | ||
| **Why `defineTool`?** | ||
| Why `defineTool`? | ||
| With Zod v4, TypeScript cannot infer concrete schema types across module boundaries when using generic `z.ZodType`. The `defineTool` helper captures specific schema types at the call site, enabling proper type inference without manual type assertions. | ||
| ### Alternative: Object Syntax with Type Assertions | ||
| ### Alternative: object syntax with type assertions | ||
| If you prefer not to use `defineTool`, you can use the object syntax directly, but you'll need type assertions: | ||
| ```ts | ||
| // Define schema separately | ||
| const searchInput = z.object({ | ||
@@ -100,3 +156,2 @@ query: z.string(), | ||
| handler: async (input) => { | ||
| // Manual type assertion required | ||
| const typed = input as z.infer<typeof searchInput>; | ||
@@ -110,67 +165,6 @@ return { results: await search(typed.query, typed.maxResults) }; | ||
| ## Zod v4 Schema Descriptions | ||
| Use `.describe()` to add descriptions that appear in tool parameter documentation: | ||
| ```ts | ||
| const myTool = defineTool({ | ||
| description: "Search for items", | ||
| input: z.object({ | ||
| query: z.string().describe("Search query text"), | ||
| maxResults: z.number().optional().describe("Maximum number of results to return"), | ||
| }), | ||
| handler: async (input) => { | ||
| // input is fully typed | ||
| return { results: [] }; | ||
| }, | ||
| }); | ||
| ``` | ||
| ## Attach UI to tool outputs | ||
| Tools can optionally reference a UI resource by ID (e.g. `"restaurant-list"`). The host can then render the returned HTML as a widget. | ||
| A common pattern is to return both: | ||
| - the model-visible output (typed by your Zod `output` schema), and | ||
| - UI-only payload in `_meta`. | ||
| ```ts | ||
| import { createApp } from "@mcp-apps-kit/core"; | ||
| import { z } from "zod"; | ||
| const app = createApp({ | ||
| name: "restaurant-finder", | ||
| version: "1.0.0", | ||
| tools: { | ||
| search_restaurants: { | ||
| description: "Search for restaurants by location", | ||
| input: z.object({ location: z.string() }), | ||
| output: z.object({ count: z.number() }), | ||
| handler: async ({ location }) => { | ||
| const restaurants = await fetchRestaurants(location); | ||
| return { | ||
| count: restaurants.length, | ||
| _meta: { restaurants }, | ||
| }; | ||
| }, | ||
| ui: "restaurant-list", | ||
| }, | ||
| }, | ||
| ui: { | ||
| "restaurant-list": { | ||
| html: "./dist/widget.html", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
| ## Plugins, Middleware & Events | ||
| Extend your app with cross-cutting concerns (logging, authentication, analytics) using plugins, middleware, and events. | ||
| ### Plugins | ||
| Plugins provide hooks into the application lifecycle and tool execution: | ||
| ```ts | ||
@@ -182,27 +176,11 @@ import { createPlugin } from "@mcp-apps-kit/core"; | ||
| version: "1.0.0", | ||
| // Lifecycle hooks | ||
| onInit: async () => console.log("App initializing..."), | ||
| onStart: async () => console.log("App started"), | ||
| // Tool execution hooks | ||
| beforeToolCall: async (context) => { | ||
| console.log(`Tool called: ${context.toolName}`); | ||
| }, | ||
| afterToolCall: async (context, result) => { | ||
| afterToolCall: async (context) => { | ||
| console.log(`Tool completed: ${context.toolName}`); | ||
| }, | ||
| onToolError: async (context, error) => { | ||
| console.error(`Tool failed: ${context.toolName}`, error); | ||
| }, | ||
| }); | ||
| const app = createApp({ | ||
| name: "my-app", | ||
| version: "1.0.0", | ||
| plugins: [loggingPlugin], | ||
| tools: { | ||
| /* ... */ | ||
| }, | ||
| }); | ||
| ``` | ||
@@ -212,25 +190,13 @@ | ||
| Middleware processes requests in a pipeline, similar to Express or Koa: | ||
| ```ts | ||
| import type { Middleware } from "@mcp-apps-kit/core"; | ||
| // Request logging middleware | ||
| const logger: Middleware = async (context, next) => { | ||
| const start = Date.now(); | ||
| console.log(`Processing ${context.toolName}...`); | ||
| // Store data in context.state (shared with other middleware & handler) | ||
| context.state.set("startTime", start); | ||
| await next(); // Call next middleware or tool handler | ||
| const duration = Date.now() - start; | ||
| console.log(`${context.toolName} completed in ${duration}ms`); | ||
| await next(); | ||
| console.log(`${context.toolName} completed in ${Date.now() - start}ms`); | ||
| }; | ||
| // Register middleware (executed in order) | ||
| app.use(logger); | ||
| app.use(rateLimiter); | ||
| app.use(authenticator); | ||
| ``` | ||
@@ -240,36 +206,12 @@ | ||
| Listen to application events for analytics and monitoring: | ||
| ```ts | ||
| // Track application lifecycle | ||
| app.on("app:init", ({ config }) => { | ||
| console.log(`App initialized: ${config.name}`); | ||
| }); | ||
| app.on("app:start", ({ transport }) => { | ||
| console.log(`Started with transport: ${transport}`); | ||
| }); | ||
| // Monitor tool execution | ||
| app.on("tool:called", ({ toolName, input }) => { | ||
| app.on("tool:called", ({ toolName }) => { | ||
| analytics.track("tool_called", { tool: toolName }); | ||
| }); | ||
| app.on("tool:success", ({ toolName, duration }) => { | ||
| metrics.timing("tool_duration", duration, { tool: toolName }); | ||
| }); | ||
| app.on("tool:error", ({ toolName, error }) => { | ||
| errorTracker.report(error, { tool: toolName }); | ||
| }); | ||
| ``` | ||
| **See the [kanban-mcp-example](https://github.com/AndurilCode/kanban-mcp-example) for a complete demonstration.** | ||
| ## Debug Logging | ||
| Enable debug logging to receive structured logs from client UIs through the MCP protocol. This is especially useful in sandboxed environments (like mobile ChatGPT) where `console` access is restricted. | ||
| Enable debug logging to receive structured logs from client UIs through the MCP protocol. | ||
| ### Server Configuration | ||
| ```ts | ||
@@ -284,4 +226,4 @@ const app = createApp({ | ||
| debug: { | ||
| logTool: true, // Enable debug logging | ||
| level: "debug", // "debug" | "info" | "warn" | "error" | ||
| logTool: true, | ||
| level: "debug", | ||
| }, | ||
@@ -292,42 +234,17 @@ }, | ||
| When enabled, the server: | ||
| You can also use the server-side logger directly: | ||
| - Registers an internal `log_debug` tool (hidden from the model) | ||
| - Receives batched log entries from connected client UIs | ||
| - Outputs logs to the server console with timestamps and source info | ||
| ### Log Levels | ||
| | Level | Description | | ||
| | ------- | ----------------------------- | | ||
| | `debug` | All logs including debug info | | ||
| | `info` | Info, warning, and error logs | | ||
| | `warn` | Warning and error logs only | | ||
| | `error` | Error logs only | | ||
| ### Using the Debug Logger (Server-side) | ||
| You can also use the debug logger directly in your server code: | ||
| ```ts | ||
| import { debugLogger } from "@mcp-apps-kit/core"; | ||
| // Log messages at different levels | ||
| debugLogger.debug("Processing request", { requestId: "123" }); | ||
| debugLogger.info("User logged in", { userId: "456" }); | ||
| debugLogger.warn("Rate limit approaching", { remaining: 10 }); | ||
| debugLogger.error("Database connection failed", { error: err.message }); | ||
| ``` | ||
| **See also:** [@mcp-apps-kit/ui README](../ui/README.md) for client-side logging. | ||
| ## OAuth 2.1 Authentication | ||
| Secure your MCP server with OAuth 2.1 bearer token validation. The framework includes built-in JWT verification with automatic JWKS discovery, complying with RFC 6750 (Bearer Token Usage) and RFC 8414 (Authorization Server Metadata). | ||
| Core validates bearer tokens and injects auth metadata for tool handlers. | ||
| ### Quick Start | ||
| ### Quick start | ||
| ```ts | ||
| import { createApp } from "@mcp-apps-kit/core"; | ||
| const app = createApp({ | ||
@@ -339,6 +256,8 @@ name: "my-app", | ||
| }, | ||
| oauth: { | ||
| protectedResource: "http://localhost:3000", | ||
| authorizationServer: "https://auth.example.com", | ||
| scopes: ["mcp:read", "mcp:write"], // Optional: required scopes | ||
| config: { | ||
| oauth: { | ||
| protectedResource: "http://localhost:3000", | ||
| authorizationServer: "https://auth.example.com", | ||
| scopes: ["mcp:read", "mcp:write"], | ||
| }, | ||
| }, | ||
@@ -348,31 +267,6 @@ }); | ||
| ### Configuration | ||
| ### Auth context access | ||
| | Option | Type | Required | Description | | ||
| | --------------------- | -------------------- | -------- | --------------------------------------------------------------- | | ||
| | `protectedResource` | `string` | ✅ | Public URL of this MCP server (used as default audience) | | ||
| | `authorizationServer` | `string` | ✅ | Issuer URL of OAuth 2.1 authorization server | | ||
| | `jwksUri` | `string` | ❌ | Explicit JWKS URI (auto-discovered if not provided) | | ||
| | `algorithms` | `string[]` | ❌ | Allowed JWT algorithms (default: `["RS256"]`) | | ||
| | `audience` | `string \| string[]` | ❌ | Expected audience claim (default: `protectedResource`) | | ||
| | `scopes` | `string[]` | ❌ | Required OAuth scopes for all requests | | ||
| | `tokenVerifier` | `TokenVerifier` | ❌ | Custom token verification (for non-JWT tokens or introspection) | | ||
| OAuth metadata is injected into `_meta` and surfaced via `context.subject` and `context.raw`: | ||
| ### How It Works | ||
| 1. **Automatic Discovery**: Framework discovers JWKS endpoint via `/.well-known/oauth-authorization-server` | ||
| 2. **Request Validation**: Bearer tokens are validated before tool execution | ||
| 3. **Auth Context Injection**: Authenticated user info is injected into tool handlers | ||
| > **Important**: This server is a **protected resource** (API/service that requires OAuth tokens), NOT an authorization server. The OAuth endpoints exposed by this framework provide metadata about the external authorization server that issues tokens, not authentication functionality itself. | ||
| #### OAuth Metadata Endpoints | ||
| When OAuth is enabled, the framework exposes two metadata endpoints: | ||
| - **`/.well-known/oauth-authorization-server`**: Returns metadata about your external authorization server (e.g., Auth0, Keycloak) | ||
| - **`/.well-known/oauth-protected-resource`**: Returns metadata about this protected resource (scopes, authorization servers) | ||
| These endpoints help clients discover OAuth configuration, but do not provide token issuance or user authentication. | ||
| ```ts | ||
@@ -383,11 +277,18 @@ tools: { | ||
| input: z.object({}), | ||
| handler: async (input, context) => { | ||
| // Access authenticated user information | ||
| const auth = context.auth; | ||
| handler: async (_input, context) => { | ||
| const subject = context.subject; | ||
| const auth = context.raw?.["mcp-apps-kit/auth"] as | ||
| | { | ||
| subject: string; | ||
| scopes: string[]; | ||
| expiresAt: number; | ||
| clientId: string; | ||
| issuer: string; | ||
| audience: string | string[]; | ||
| token?: string; | ||
| extra?: Record<string, unknown>; | ||
| } | ||
| | undefined; | ||
| console.log("User ID:", auth.subject); | ||
| console.log("Scopes:", auth.scopes); | ||
| console.log("Expires at:", new Date(auth.expiresAt * 1000)); | ||
| return { userId: auth.subject }; | ||
| return { userId: subject, scopes: auth?.scopes ?? [] }; | ||
| }, | ||
@@ -398,38 +299,13 @@ }), | ||
| ### Auth Context Properties | ||
| ### OAuth metadata endpoints | ||
| When OAuth is enabled, tool handlers receive authenticated context via `context.auth`: | ||
| When OAuth is enabled, the server exposes: | ||
| ```ts | ||
| interface AuthContext { | ||
| subject: string; // User identifier (JWT 'sub' claim) | ||
| scopes: string[]; // OAuth scopes granted to token | ||
| expiresAt: number; // Token expiration (Unix timestamp) | ||
| clientId: string; // OAuth client ID | ||
| issuer: string; // Token issuer (authorization server) | ||
| audience: string | string[]; // Token audience | ||
| token?: string; // Original bearer token | ||
| extra?: Record<string, unknown>; // Additional JWT claims | ||
| } | ||
| ``` | ||
| - `/.well-known/oauth-authorization-server` | ||
| - `/.well-known/oauth-protected-resource` | ||
| ### Error Responses | ||
| These endpoints describe the external authorization server and this protected resource. They do not issue tokens. | ||
| The framework returns RFC 6750-compliant error responses: | ||
| ### Custom token verification | ||
| ```http | ||
| HTTP/1.1 401 Unauthorized | ||
| WWW-Authenticate: Bearer realm="http://localhost:3000", | ||
| error="invalid_token", | ||
| error_description="Token expired" | ||
| ``` | ||
| | Error Code | Status | Description | | ||
| | -------------------- | ------ | ------------------------------------ | | ||
| | `invalid_request` | 400 | Malformed request | | ||
| | `invalid_token` | 401 | Token expired, revoked, or malformed | | ||
| | `insufficient_scope` | 403 | Token missing required scopes | | ||
| ### Custom Token Verification | ||
| For non-JWT tokens or token introspection: | ||
@@ -442,3 +318,2 @@ | ||
| async verifyAccessToken(token: string) { | ||
| // Call your token introspection endpoint | ||
| const response = await fetch("https://auth.example.com/introspect", { | ||
@@ -466,31 +341,50 @@ method: "POST", | ||
| const app = createApp({ | ||
| oauth: { | ||
| protectedResource: "http://localhost:3000", | ||
| authorizationServer: "https://auth.example.com", | ||
| tokenVerifier: customVerifier, // Use custom verifier | ||
| name: "my-app", | ||
| version: "1.0.0", | ||
| tools: { | ||
| /* ... */ | ||
| }, | ||
| config: { | ||
| oauth: { | ||
| protectedResource: "http://localhost:3000", | ||
| authorizationServer: "https://auth.example.com", | ||
| tokenVerifier: customVerifier, | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
| ### Security Features | ||
| ### Security features | ||
| - ✅ **JWT Signature Verification**: RSA/ECDSA signature validation via JWKS | ||
| - ✅ **Claim Validation**: Automatic validation of `iss`, `aud`, `exp`, `sub`, `client_id` | ||
| - ✅ **Scope Enforcement**: Optional scope validation for all requests | ||
| - ✅ **Issuer Normalization**: Handles trailing slash differences | ||
| - ✅ **Clock Skew Tolerance**: 5-second tolerance for timestamp validation | ||
| - ✅ **HTTPS Enforcement**: JWKS URIs must use HTTPS in production | ||
| - ✅ **Subject Override**: Framework overrides client-provided subject for security | ||
| - JWT signature verification via JWKS | ||
| - Claim validation for `iss`, `aud`, `exp`, `sub`, `client_id` | ||
| - Optional scope enforcement | ||
| - Issuer normalization and clock skew tolerance | ||
| - HTTPS enforcement for JWKS in production | ||
| - Subject override for client-provided identity metadata | ||
| ### Production Considerations | ||
| ### Production considerations | ||
| 1. **HTTPS Required**: JWKS URIs must use HTTPS in production environments | ||
| 2. **Key Caching**: JWKS keys are cached with automatic refresh (10-minute TTL) | ||
| 3. **Rate Limiting**: Built-in rate limiting for JWKS requests (10 requests/minute) | ||
| 4. **Error Handling**: All validation errors return proper WWW-Authenticate headers | ||
| 1. JWKS keys are cached with automatic refresh (10-minute TTL) | ||
| 2. JWKS requests are rate limited (10 requests/minute) | ||
| 3. Validation errors return RFC 6750-compliant WWW-Authenticate headers | ||
| ### Testing Without OAuth | ||
| ### Testing without OAuth | ||
| Disable OAuth for development/testing: | ||
| ```ts | ||
| const app = createApp({ | ||
| name: "my-app", | ||
| version: "1.0.0", | ||
| tools: { | ||
| /* ... */ | ||
| }, | ||
| }); | ||
| ``` | ||
| ## OpenAI Domain Verification | ||
| When submitting your app to the ChatGPT App Store, OpenAI requires domain verification to confirm ownership of the MCP server host. | ||
| ### Configuration | ||
| ```ts | ||
@@ -503,22 +397,51 @@ const app = createApp({ | ||
| }, | ||
| // No oauth config = OAuth disabled | ||
| config: { | ||
| openai: { | ||
| domain_challenge: "your-verification-token-from-openai", | ||
| }, | ||
| }, | ||
| }); | ||
| ``` | ||
| ## What you get | ||
| ### How it works | ||
| - A single place to define **tools** + **UI resources** | ||
| - Runtime validation via Zod + strong TypeScript inference | ||
| - Protocol-aware metadata generation for both Claude and ChatGPT hosts | ||
| 1. Register your app on the OpenAI Platform to receive a verification token | ||
| 2. Set the token in `config.openai.domain_challenge` | ||
| 3. The framework exposes `GET /.well-known/openai-apps-challenge` returning the token as plain text | ||
| 4. OpenAI pings the endpoint during submission to verify domain ownership | ||
| ## Documentation & examples | ||
| ### Notes | ||
| - Project overview: ../../README.md | ||
| - Examples: | ||
| - [kanban-mcp-example](https://github.com/AndurilCode/kanban-mcp-example) (comprehensive demo) | ||
| - ../../examples/minimal | ||
| - ../../examples/restaurant-finder | ||
| - Deploy before submitting so the endpoint is live | ||
| - The endpoint returns `text/plain` as required | ||
| - Works in Express and serverless deployments (`handleRequest`) | ||
| ### References | ||
| - [OpenAI Apps SDK - Submit your app](https://developers.openai.com/apps-sdk/deploy/submission/) | ||
| - [OpenAI Help Center - Domain Verification](https://help.openai.com/en/articles/8871611-domain-verification) | ||
| ## Examples | ||
| - `../../examples/minimal` | ||
| - `../../examples/restaurant-finder` | ||
| - [kanban-mcp-example](https://github.com/AndurilCode/kanban-mcp-example) | ||
| ## API | ||
| Key exports include: | ||
| - `createApp`, `defineTool`, `defineUI` | ||
| - `createPlugin`, `loggingPlugin` | ||
| - `debugLogger`, `ClientToolsFromCore` | ||
| - `Middleware`, `TypedEventEmitter` | ||
| For full types, see `packages/core/src/types` or the project overview in `../../README.md`. | ||
| ## Contributing | ||
| See `../../CONTRIBUTING.md` for development setup and guidelines. Issues and pull requests are welcome. | ||
| ## License | ||
| MIT |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
801184
0.7%7476
1.38%428
-15.25%