diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6848e4c..fb41938 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,21 +114,6 @@ jobs: grep -q "Ready" /tmp/mcpb-smoke.log working-directory: examples/pdf-server - dependency-isolation: - name: Dependency isolation - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - - uses: actions/setup-node@v6 - with: - node-version: "22" - cache: npm - - - run: npm ci - - - run: npm run test:dependency-isolation - e2e: runs-on: ubuntu-latest steps: @@ -147,10 +132,8 @@ jobs: - run: npm ci - # Headless runs without a channel use chromium-headless-shell, so the - # full Chromium build (about 165 MB) would only be downloaded, never run. - name: Install Playwright browsers - run: npx playwright install --with-deps --only-shell chromium + run: npx playwright install --with-deps chromium - name: Run E2E tests run: npx playwright test --reporter=list @@ -182,14 +165,9 @@ jobs: curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - sudo apt-get install -y nodejs - # The checkout lives on the Windows drive, which WSL reaches over 9P; - # writing node_modules there is what makes this job slow (npm ci alone - # took about 3 minutes). Copy the tree onto the distro's ext4 filesystem - # first, as Microsoft's WSL guidance recommends for anything I/O heavy. - name: Build and test in WSL shell: wsl-bash {0} run: | - cp -r "$(pwd)" ~/ext-apps && cd ~/ext-apps npm ci npm run build npm run examples:build diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index ed36c15..ece35d3 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -42,10 +42,6 @@ jobs: - run: npm ci - run: npm test - # All publish jobs depend directly on [build, test] (not on each other) so - # they all enter "waiting for approval" together and can be approved in a - # single "Review deployments" click. - publish: runs-on: ubuntu-latest if: github.event_name == 'release' @@ -92,7 +88,7 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'release' environment: Release - needs: [build, test] + needs: [publish] permissions: contents: read @@ -112,7 +108,6 @@ jobs: - cohort-heatmap-server - customer-segmentation-server - debug-server - - lazy-auth-server - map-server - pdf-server - scenario-modeler-server @@ -139,18 +134,8 @@ jobs: - name: Build example run: npm run build --workspace examples/${{ matrix.example }} - - name: Determine npm tag - id: npm-tag - run: | - VERSION=$(node -p "require('./package.json').version") - if [[ "$VERSION" == *"-"* ]]; then - echo "tag=--tag beta" >> $GITHUB_OUTPUT - else - echo "tag=" >> $GITHUB_OUTPUT - fi - - name: Publish example - run: npm publish --workspace examples/${{ matrix.example }} --provenance --access public ${{ steps.npm-tag.outputs.tag }} + run: npm publish --workspace examples/${{ matrix.example }} --provenance --access public env: NODE_AUTH_TOKEN: ${{ secrets.NPM_SECRET }} @@ -158,7 +143,7 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'release' environment: Release - needs: [build, test] + needs: [publish-examples] permissions: contents: write diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 478c5b8..5f1d3ac 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -34,7 +34,6 @@ jobs: ./examples/cohort-heatmap-server \ ./examples/customer-segmentation-server \ ./examples/debug-server \ - ./examples/lazy-auth-server \ ./examples/map-server \ ./examples/pdf-server \ ./examples/scenario-modeler-server \ diff --git a/.husky/pre-commit b/.husky/pre-commit index ae5b3c7..b0d5ff5 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -15,9 +15,8 @@ if grep -E '"resolved": "https?://' package-lock.json | grep -v registry.npmjs.o fi # Capture staged files so we only re-stage what the user intended to commit -# (avoids sweeping unrelated WIP into the commit). --diff-filter=d skips -# deletions so the xargs git add below doesn't fail on removed paths. -STAGED=$(git diff --name-only --cached --diff-filter=d) +# (avoids sweeping unrelated WIP into the commit) +STAGED=$(git diff --name-only --cached) npm run build:all npm run prettier:fix diff --git a/.prettierignore b/.prettierignore index c51df7b..6d5fc6f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,5 +5,4 @@ examples/basic-server-*/**/*.tsx examples/quickstart/**/*.ts **/vendor/** **/.build/** -**/.claude/** SKILL.md diff --git a/AGENTS.md b/AGENTS.md index 219b947..6bfc8cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,8 +60,8 @@ rm -fR package-lock.json node_modules && \ ### Key Source Files -- `src/app.ts` - `App` subclasses `Protocol` from `@modelcontextprotocol/client`, handles View initialization, tool calls, and messaging -- `src/app-bridge.ts` - `AppBridge` subclasses `Protocol` from `@modelcontextprotocol/client` for the iframe channel and proxies through a separate outer `Client` +- `src/app.ts` - `App` class extends MCP Protocol, handles guest initialization, tool calls, messaging +- `src/app-bridge.ts` - `AppBridge` class for hosts, proxies MCP requests, sends tool input/results to guests - `src/server/index.ts` - Helpers for MCP servers to register tools/resources with UI metadata - `src/types.ts` - Protocol types re-exported from `spec.types.ts` and Zod schemas from `generated/schema.ts` (auto-generated during build) - `src/message-transport.ts` - `PostMessageTransport` for iframe communication @@ -70,12 +70,12 @@ rm -fR package-lock.json node_modules && \ ### Protocol Flow ``` -View (App/Protocol) <--PostMessageTransport--> Host (AppBridge/Protocol) <--separate MCP Client--> MCP Server +View (App) <--PostMessageTransport--> Host (AppBridge) <--MCP Client--> MCP Server ``` 1. Host creates iframe with view HTML 2. View creates `App` instance and calls `connect()` with `PostMessageTransport` -3. View sends `ui/initialize` (the only handshake on the iframe channel) and receives authoritative Apps capabilities and context +3. View sends `ui/initialize` request, receives host capabilities and context 4. Host sends `sendToolInput()` with tool arguments after initialization 5. View can call server tools via `app.callServerTool()` or send messages via `app.sendMessage()` 6. Host sends `sendToolResult()` when tool execution completes diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e28dcd1..7ca6368 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,14 +27,6 @@ We welcome contributions to the MCP Apps SDK! This document outlines the process - Provide a clear description of changes - **Keep "Allow edits by maintainers" checked** when opening your PR — this lets maintainers rebase your branch and lets the [`/update-snapshots` workflow](#updating-snapshots-in-ci) push updated screenshots to it -## Examples Policy - -The examples in `examples/` are maintained by the core team. **We do not accept pull requests that add new example servers from outside contributors.** Each example carries an ongoing maintenance cost — keeping it building, tested, and up to date with SDK changes — so we are deliberate about what we add. - -If you have an idea for an example that would provide significant educational value, please [open an issue](https://github.com/modelcontextprotocol/ext-apps/issues) describing what the example would demonstrate and why it would be useful, and maintainers will evaluate the request. - -PRs that add new examples without a prior approved issue may be closed. - ## Running Examples Start the development environment with hot reloading: @@ -502,7 +494,7 @@ Alternatively, use the [workflow dispatch](https://github.com/modelcontextprotoc ## Code of Conduct -This project follows our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md). Please review it before contributing. +This project follows our [Code of Conduct](CODE_OF_CONDUCT.md). Please review it before contributing. ## Reporting Issues @@ -539,17 +531,40 @@ Before publishing releases, ensure the following are configured: ### Publishing a Release -1. **Bump the version** across the root and all workspace packages: +Releases are published automatically via GitHub Actions when a GitHub Release is created. + +#### Steps to publish: + +1. **Update the version** in `package.json`: ```bash - npm run bump -- minor # or: patch | major | prerelease --preid=beta | 1.7.0 + # For a regular release + npm version patch # or minor, or major + + # For a beta release + npm version prerelease --preid=beta ``` - Commit and open a PR with a grouped changelog in the body (see prior `chore: bump …` PRs for the format). +2. **Commit the version bump** (if not done by `npm version`): -2. **Merge the PR**, then [draft a GitHub Release](https://github.com/modelcontextprotocol/ext-apps/releases/new) — create a `vX.Y.Z` tag on `main`, paste the changelog, publish. + ```bash + git add package.json + git commit -m "Bump version to X.Y.Z" + git push origin main + ``` -3. **Approve the deployment** — publishing the Release triggers the [npm-publish workflow](https://github.com/modelcontextprotocol/ext-apps/actions/workflows/npm-publish.yml); all publish jobs wait together for a single "Review deployments" approval. +3. **Create a GitHub Release**: + - Go to [Releases](https://github.com/modelcontextprotocol/ext-apps/releases) + - Click "Draft a new release" + - Create a new tag matching the version (e.g., `v0.1.0`) + - Set the target branch (usually `main`) + - Write release notes describing the changes + - Click "Publish release" + +4. **Monitor the workflow**: + - The [npm-publish workflow](https://github.com/modelcontextprotocol/ext-apps/actions/workflows/npm-publish.yml) will trigger automatically + - It runs build and test jobs before publishing + - On success, the package is published to npm with provenance #### npm Tags @@ -573,7 +588,7 @@ To release a patch for an older version: ### Testing Pre-releases -Every commit and PR automatically publishes a preview package via [pkg-pr-new](https://github.com/stackblitz-labs/pkg.pr.new). Check the PR comments or workflow logs for the install command. +Every commit and PR automatically publishes a preview package via [pkg-pr-new](https://github.com/pkg-pr-new/pkg-pr-new). Check the PR comments or workflow logs for the install command. --- diff --git a/README.md b/README.md index ab4004d..7348e15 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

Why · - Quickstart + Quickstart · API Docs · @@ -89,8 +89,6 @@ it will guide you through the rest. Goose Postman MCPJam - mcp-use - Alpic Playground

> [!NOTE] @@ -122,36 +120,12 @@ resources: ## Getting Started -Requires Node.js 20+. The base MCP SDK packages are `^2.0.0` peers of -`ext-apps` (`@modelcontextprotocol/core` is a required peer that `client` already depends on, so npm installs it for you). - -For a View or host: - ```bash -npm install -S @modelcontextprotocol/ext-apps \ - @modelcontextprotocol/client@^2.0.0 \ - zod@^4.2.0 +npm install -S @modelcontextprotocol/ext-apps ``` -For an MCP server, add the server package (and, for HTTP transports, the Node -and Express adapters): - -```bash -npm install -S @modelcontextprotocol/ext-apps \ - @modelcontextprotocol/client@^2.0.0 \ - @modelcontextprotocol/server@^2.0.0 \ - @modelcontextprotocol/node@^2.0.0 \ - @modelcontextprotocol/express@^2.0.0 \ - zod@^4.2.0 -``` - -The wire protocol is unchanged between `ext-apps` 1.x and 2.x: a 2.x View works -in a 1.x host and a 2.x host renders 1.x Views. See the -[migration guide](https://apps.extensions.modelcontextprotocol.io/api/documents/migrate-to-v2.html) -when upgrading from 1.x. - **New here?** Start with the -[Quickstart Guide](https://apps.extensions.modelcontextprotocol.io/api/documents/quickstart.html) +[Quickstart Guide](https://apps.extensions.modelcontextprotocol.io/api/documents/Quickstart.html) to build your first MCP App. ## Using the SDK @@ -165,7 +139,7 @@ UI metadata. | `@modelcontextprotocol/ext-apps` | Build interactive Views (App class, PostMessageTransport) | [API Docs →](https://apps.extensions.modelcontextprotocol.io/api/modules/app.html) | | `@modelcontextprotocol/ext-apps/react` | React hooks for Views (useApp, useHostStyles, etc.) | [API Docs →](https://apps.extensions.modelcontextprotocol.io/api/modules/_modelcontextprotocol_ext-apps_react.html) | | `@modelcontextprotocol/ext-apps/app-bridge` | Embed and communicate with Views in your chat client | [API Docs →](https://apps.extensions.modelcontextprotocol.io/api/modules/app-bridge.html) | -| `@modelcontextprotocol/ext-apps/server` | Register tools and resources on your MCP server | [API Docs →](https://apps.extensions.modelcontextprotocol.io/api/modules/server-helpers.html) | +| `@modelcontextprotocol/ext-apps/server` | Register tools and resources on your MCP server | [API Docs →](https://apps.extensions.modelcontextprotocol.io/api/modules/server.html) | There's no _supported_ host implementation in this repo (beyond the [examples/basic-host](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) @@ -272,7 +246,7 @@ point your client at a local build: ## Resources -- [Quickstart Guide](https://apps.extensions.modelcontextprotocol.io/api/documents/quickstart.html) +- [Quickstart Guide](https://apps.extensions.modelcontextprotocol.io/api/documents/Quickstart.html) - [API Documentation](https://apps.extensions.modelcontextprotocol.io/api/) - [Specification (2026-01-26)](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx) ([Draft](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx)) diff --git a/build.bun.ts b/build.bun.ts index 61361e6..a129d5d 100644 --- a/build.bun.ts +++ b/build.bun.ts @@ -1,9 +1,6 @@ #!/usr/bin/env bun import { $ } from "bun"; -import { cpSync, mkdirSync, rmSync } from "node:fs"; - -// Avoid publishing artifacts left behind by an earlier build or branch. -rmSync("dist", { recursive: true, force: true }); +import { cpSync, mkdirSync } from "node:fs"; // Run TypeScript compiler for type declarations await $`tsc`; @@ -34,15 +31,9 @@ function buildJs( }); } -// Peer dependencies stay external in the standard entry points so consumers -// share one base MCP SDK and Zod instance. The *-with-deps entry points keep -// bundling these dependencies for standalone browser use. -const PEER_EXTERNALS = [ - "@modelcontextprotocol/client", - "@modelcontextprotocol/core", - "@modelcontextprotocol/server", - "zod", -]; +// zod is a peerDependency — keep it external so consumers share a single +// zod instance (instanceof ZodError / schema.extend() break with duplicate copies). +const PEER_EXTERNALS = ["@modelcontextprotocol/sdk", "zod"]; await Promise.all([ buildJs("src/app.ts", { diff --git a/docs/authorization.md b/docs/authorization.md index df7adc6..59fc26c 100644 --- a/docs/authorization.md +++ b/docs/authorization.md @@ -150,7 +150,7 @@ registerAppTool( "get_account_balance", { description: "Get account balance", - inputSchema: z.object({ accountId: z.string() }), + inputSchema: { accountId: z.string() }, }, async ({ accountId }) => { if (!authInfo) { diff --git a/docs/migrate-to-2.md b/docs/migrate-to-2.md deleted file mode 100644 index f9341d0..0000000 --- a/docs/migrate-to-2.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Migrate to v2 -group: Getting Started -description: Upgrade from ext-apps 1.x to 2.x — new base MCP SDK peer packages, API changes for Views and hosts, and what stays wire-compatible. ---- - -# Migrating from ext-apps 1.x to 2.x - -ext-apps 2.x is built on the base MCP TypeScript SDK 2.x, which replaced the -single `@modelcontextprotocol/sdk` package with `@modelcontextprotocol/client`, -`server`, `core`, `node` and `express`. The MCP Apps wire protocol did not -change; the breaking changes are in dependencies and in the TypeScript API. - -## Host compatibility - -The `ui/*` messages exchanged over the iframe channel are byte-identical to -1.x. A 2.x View runs in a 1.x host and a 2.x host renders 1.x Views. The only -host-side deltas are in error responses (see below). - -## What stays the same - -`App` / `AppBridge` constructors, the `on*` setters, `addEventListener`, -`callServerTool`, `readServerResource`, `registerAppResource`, the React hooks -and the `_meta.ui.resourceUri` handling are unchanged. Published `.d.ts` files -now resolve under `moduleResolution: NodeNext` / `Node16` without workarounds -(#705). - -## Peer dependencies by role - -| Role | Install | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| View author | `@modelcontextprotocol/ext-apps`, `@modelcontextprotocol/client@^2.0.0`, `zod@^4.2.0` (+ `react`/`react-dom` for `./react`) | -| Host author | same as View author | -| MCP server author | View author packages + `@modelcontextprotocol/server@^2.0.0`; for HTTP transports also `@modelcontextprotocol/node@^2.0.0` (`NodeStreamableHTTPServerTransport`) and `@modelcontextprotocol/express@^2.0.0` (`createMcpExpressApp`, which peers on `express`) | -| CDN / `*-with-deps` | nothing extra: `./app-with-deps` and `./react-with-deps` bundle client, core and zod (about 25% larger than the 1.x bundles) | - -`@modelcontextprotocol/client` is a required peer (`App` and `AppBridge` extend -its `Protocol` class); `@modelcontextprotocol/core` is a required peer that `client` already depends on, so npm installs it without you listing it; -`@modelcontextprotocol/server` stays optional and is only needed for the -`./server` helpers. Node.js 20+ is required. - -## Breaking changes - -- **Peer packages.** `@modelcontextprotocol/sdk@^1` is replaced by the split - 2.x packages above, all at `^2.0.0`. Remove the 1.x package from your - project: the two SDKs share no classes or types (a 1.x `McpError` or - `Client` cannot be passed to 2.x code), even though they speak the same - wire protocol. -- **zod 3 dropped.** The peer range is `zod@^4.2.0`. Tool schemas must - implement Standard JSON Schema (`~standard.jsonSchema`): zod 4.2+, ArkType, - Valibot. zod 4.0 and 4.1 do not expose `~standard.jsonSchema` and are - rejected too. Raw zod shapes (`{ q: z.string() }`) still work with - `registerAppTool` but are deprecated; wrap them with `z.object({...})`. -- **`App` / `AppBridge` extend `Protocol` from `@modelcontextprotocol/client`.** - `ProtocolWithEvents` is gone; use the SDK's `Protocol`. The `AppRequest`, - `AppNotification` and `AppResult` unions are kept as deprecated type - aliases (nothing in 2.x consumes them) and will be removed in 3.0. -- **Handler context.** Custom request handlers, `registerAppTool` callbacks - (server) and `app.registerTool` callbacks (View) receive the SDK 2.x - context: `extra.signal` → `extra.mcpReq.signal`, `extra.requestId` → - `extra.mcpReq.id`; `extra.sessionId` is unchanged and `extra.authInfo` - moved to `extra.http?.authInfo`. -- **`setRequestHandler` / `setNotificationHandler` take method names.** - `app.setRequestHandler(SomeRequestSchema, handler)` becomes - `app.setRequestHandler("some/method", { params: SomeParamsSchema }, (params, ctx) => …)` - for custom methods (the handler receives the parsed params); the two-argument - `setRequestHandler("tools/call", handler)` form exists only for spec-defined - method names. The 1.x `(Schema, handler)` form still works on `App` and - `AppBridge` as a deprecated overload: it logs a one-time warning, hands the - handler the whole `{ method, params }` message as before, and gives request - handlers a 1.x-shaped `extra` (`signal`, `requestId`, `sessionId`, `_meta`, - `sendRequest`, `sendNotification`, `authInfo`; exported as - `LegacyRequestHandlerExtra`). It will be removed in 3.0. -- **Double-registration guard covers the SDK's own handlers.** Registering a - handler for `notifications/progress` or `notifications/cancelled` (which - the base `Protocol` already owns) now throws `already registered`, as - `ping` and the `on*`-owned methods did in 1.x. Use `addEventListener` or - the SDK's progress callbacks instead of replacing these. -- **Errors.** Remote JSON-RPC errors are `ProtocolError` (numeric `code`); - local conditions are `SdkError` with a string `code`: request timeout → - `"REQUEST_TIMEOUT"`, connection closed → `"CONNECTION_CLOSED"`. Cancelling a - request with an `AbortSignal` also rejects with `"REQUEST_TIMEOUT"` (the - message is the abort reason). Messages no longer carry the `MCP error N:` - prefix. - A resource-not-found reply that carries `data.uri` arrives as - `ResourceNotFoundError` (a `ProtocolError` subclass, `code` `-32602`, with a - `.uri` getter). - -## Host-side wire deltas - -Observed when a 2.x `AppBridge` answers a View; a 1.x View sees these too. - -| Situation | 1.x host | 2.x host | -| --------------------------------------------------------- | ------------------------------ | --------------------------------------------------- | -| A handler throws `-32002` (resource not found) | `error.code: -32002` | `error.code: -32602` (the SDK never emits `-32002`) | -| Invalid params on a `ui/*` request | `-32603` with a zod issue dump | `-32602 Invalid params for : …` | -| Error message text | `MCP error -32602: …` prefix | plain message | -| `tools/call` to an unknown tool through a 2.x `McpServer` | `result.isError: true` | JSON-RPC error `-32602` (`callServerTool` rejects) | - -## `schema.json` - -The published `./schema.json` export is regenerated from the 2.x core schemas: - -- `McpUiToolResultNotification.params.structuredContent` is any JSON value (was - `type: "object"`). -- `McpUiToolResultNotification.params._meta` documents - `io.modelcontextprotocol/serverInfo` and no longer lists `progressToken` / - `related-task` (both still pass through). -- `McpUiHostContext.toolInfo.tool.outputSchema` is a loose object (only - `$schema` is documented); `inputSchema.properties` values are now typed as - JSON values. -- A recursive JSON-value definition (`__schema0`) is added under the `$defs` of - `McpUiHostContext`, `McpUiHostContextChangedNotification` and - `McpUiInitializeResult`. - -## Checklist - -1. `npm uninstall @modelcontextprotocol/sdk` and install the packages for your - role from the table above. -2. Replace `sdk/...` imports with the split packages (`sdk/server/mcp.js` → - `@modelcontextprotocol/server`, `sdk/server/streamableHttp.js` → - `NodeStreamableHTTPServerTransport` from `@modelcontextprotocol/node`, - `sdk/server/stdio.js` → `@modelcontextprotocol/server/stdio`, hand-written - Express routing → `createMcpExpressApp` from `@modelcontextprotocol/express`, - `sdk/types.js` → `@modelcontextprotocol/client` or `server` for the types, - `@modelcontextprotocol/core` for the zod schemas). -3. Wrap raw zod shapes with `z.object({...})`. -4. Update custom handlers to the `extra.mcpReq.*` context and method-keyed - `setRequestHandler` calls. -5. Replace `McpError` / numeric-code checks with `ProtocolError` / `SdkError`. diff --git a/docs/migrate_from_openai_apps.md b/docs/migrate_from_openai_apps.md index 22d5d9f..d91281b 100644 --- a/docs/migrate_from_openai_apps.md +++ b/docs/migrate_from_openai_apps.md @@ -66,7 +66,7 @@ The server-side changes involve updating metadata structure and using helper fun #### Before (OpenAI) ```typescript -import { McpServer } from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { z } from "zod"; function createServer() { @@ -78,7 +78,7 @@ function createServer() { { title: "Shopping Cart", description: "Display the user's shopping cart", - inputSchema: z.object({ userId: z.string() }), + inputSchema: { userId: z.string() }, annotations: { readOnlyHint: true }, _meta: { "openai/outputTemplate": "ui://view/cart.html", @@ -126,7 +126,7 @@ function createServer() { #### After (MCP Apps) ```typescript -import { McpServer } from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { registerAppTool, registerAppResource, @@ -144,7 +144,7 @@ function createServer() { { title: "Shopping Cart", description: "Display the user's shopping cart", - inputSchema: z.object({ userId: z.string() }), + inputSchema: { userId: z.string() }, annotations: { readOnlyHint: true }, _meta: { ui: { resourceUri: "ui://view/cart.html" } }, }, diff --git a/docs/overview.md b/docs/overview.md index 8eda95d..28f5b23 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -56,11 +56,7 @@ flowchart LR - **Host** — The chat client (e.g., Claude Desktop) that connects to servers, embeds Views in iframes, and proxies communication between them. - **View** — The UI running inside a sandboxed iframe. It receives tool data from the Host and can call server tools or send messages back to the chat. -The View's `App` and the Host's `AppBridge` both subclass the `Protocol` class -exported by `@modelcontextprotocol/client` for the iframe channel. A separate outer `Client` connects -the Host to the actual MCP Server. Keeping those two connections separate -preserves the Apps-only iframe handshake and prevents iframe capabilities from -leaking into the server connection. +The View acts as an MCP client, the Host acts as a proxy, and the Server is a standard MCP server. ## Lifecycle @@ -97,7 +93,7 @@ sequenceDiagram ``` 1. **Discovery** — The Host learns about tools and their UI resources when connecting to the server. -2. **Initialization** — When a UI tool is called, the Host renders the iframe. The View sends `ui/initialize` (the only handshake on the iframe channel) and receives host context (theme, capabilities, container dimensions). `ui/initialize` is authoritative for Apps capabilities and identity, and `ui/notifications/initialized` is the public View-ready signal. +2. **Initialization** — When a UI tool is called, the Host renders the iframe. The View sends `ui/initialize` and receives host context (theme, capabilities, container dimensions). This handshake ensures the View is ready before receiving data. 3. **Data delivery** — The Host sends tool arguments and, once available, tool results to the View. Results include both `content` (text for the model's context) and optionally `structuredContent` (data optimized for UI rendering). This separation lets servers provide rich data to the UI without bloating the model's context. 4. **Interactive phase** — The user interacts with the View. The View can call tools, send messages, or update context. 5. **Teardown** — Before unmounting, the Host notifies the View so it can save state or release resources. diff --git a/docs/patterns.md b/docs/patterns.md index 884de26..87a6d82 100644 --- a/docs/patterns.md +++ b/docs/patterns.md @@ -19,7 +19,7 @@ registerAppTool( "update-quantity", { description: "Update item quantity in cart", - inputSchema: z.object({ itemId: z.string(), quantity: z.number() }), + inputSchema: { itemId: z.string(), quantity: z.number() }, _meta: { ui: { resourceUri: "ui://shop/cart.html", @@ -127,14 +127,14 @@ registerAppTool( { title: "Read Data Bytes", description: "Load binary data in chunks", - inputSchema: z.object({ + inputSchema: { id: z.string().describe("Resource identifier"), offset: z.number().min(0).default(0).describe("Byte offset"), byteCount: z .number() .default(MAX_CHUNK_BYTES) .describe("Bytes to read"), - }), + }, outputSchema: DataChunkSchema, // Hidden from model - only callable by the App _meta: { ui: { visibility: ["app"] } }, @@ -281,7 +281,10 @@ server.registerResource( ```ts source="./patterns.tsx#binaryBlobResourceClient" -const result = await app.readServerResource({ uri: `video://${videoId}` }); +const result = await app.request( + { method: "resources/read", params: { uri: `video://${videoId}` } }, + ReadResourceResultSchema, +); const content = result.contents[0]; if (!content || !("blob" in content)) { diff --git a/docs/patterns.tsx b/docs/patterns.tsx index bb9eaa4..6b87692 100644 --- a/docs/patterns.tsx +++ b/docs/patterns.tsx @@ -17,12 +17,16 @@ import { randomUUID } from "node:crypto"; import type { CallToolResult, ReadResourceResult, -} from "@modelcontextprotocol/server"; +} from "@modelcontextprotocol/sdk/types.js"; +import { ReadResourceResultSchema } from "@modelcontextprotocol/sdk/types.js"; import type { McpUiHostContext } from "../src/types.js"; import { useEffect, useState } from "react"; import { useApp } from "../src/react/index.js"; import { registerAppTool } from "../src/server/index.js"; -import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server"; +import { + McpServer, + ResourceTemplate, +} from "@modelcontextprotocol/sdk/server/mcp.js"; import { z } from "zod"; /** @@ -113,14 +117,14 @@ function chunkedDataServer(server: McpServer) { { title: "Read Data Bytes", description: "Load binary data in chunks", - inputSchema: z.object({ + inputSchema: { id: z.string().describe("Resource identifier"), offset: z.number().min(0).default(0).describe("Byte offset"), byteCount: z .number() .default(MAX_CHUNK_BYTES) .describe("Bytes to read"), - }), + }, outputSchema: DataChunkSchema, // Hidden from model - only callable by the App _meta: { ui: { visibility: ["app"] } }, @@ -248,7 +252,10 @@ function binaryBlobResourceServer( */ async function binaryBlobResourceClient(app: App, videoId: string) { //#region binaryBlobResourceClient - const result = await app.readServerResource({ uri: `video://${videoId}` }); + const result = await app.request( + { method: "resources/read", params: { uri: `video://${videoId}` } }, + ReadResourceResultSchema, + ); const content = result.contents[0]; if (!content || !("blob" in content)) { diff --git a/docs/quickstart.md b/docs/quickstart.md index a021912..3e00796 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -21,7 +21,7 @@ This tutorial assumes you've built an MCP server before and are comfortable with We'll use the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) to build the server. -You'll also need Node.js 20+. +You'll also need Node.js 18+. ## 1. Set up the project @@ -37,7 +37,7 @@ Install the dependencies you'll need: ```bash npm init -y -npm install @modelcontextprotocol/ext-apps @modelcontextprotocol/client@^2.0.0 @modelcontextprotocol/server@^2.0.0 @modelcontextprotocol/node@^2.0.0 @modelcontextprotocol/express@^2.0.0 zod@^4.2.0 express cors +npm install @modelcontextprotocol/ext-apps @modelcontextprotocol/sdk express cors npm install -D typescript vite vite-plugin-singlefile @types/express @types/cors @types/node tsx concurrently cross-env ``` @@ -59,7 +59,6 @@ npm pkg set scripts.start='concurrently --raw "cross-env NODE_ENV=development IN ```json source="../examples/quickstart/tsconfig.json" { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", @@ -88,7 +87,6 @@ npm pkg set scripts.start='concurrently --raw "cross-env NODE_ENV=development IN ```json source="../examples/quickstart/tsconfig.server.json" { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", @@ -180,10 +178,9 @@ import { registerAppTool, RESOURCE_MIME_TYPE, } from "@modelcontextprotocol/ext-apps/server"; -import { McpServer } from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import fs from "node:fs/promises"; import path from "node:path"; -import { z } from "zod"; const DIST_DIR = path.join(import.meta.dirname, "dist"); @@ -208,7 +205,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async () => { @@ -243,10 +240,10 @@ export function createServer(): McpServer { ```ts source="../examples/quickstart/main.ts" -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -266,7 +263,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/docs/testing-mcp-apps.md b/docs/testing-mcp-apps.md index a8eb333..df1396c 100644 --- a/docs/testing-mcp-apps.md +++ b/docs/testing-mcp-apps.md @@ -28,10 +28,6 @@ The [`basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/ex cd examples/basic-host ``` - The root install runs the package build, including type-checking the - documentation snippets against the pinned base MCP SDK 2.x packages. Do - not bypass a failed build before testing the host. - 2. Start basic-host, pointing it to your MCP server: ```bash diff --git a/examples/basic-host/package.json b/examples/basic-host/package.json index cefe9d5..b29f04a 100644 --- a/examples/basic-host/package.json +++ b/examples/basic-host/package.json @@ -1,7 +1,7 @@ { "homepage": "https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host", "name": "@modelcontextprotocol/ext-apps-basic-host", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "scripts": { "build": "tsc --noEmit && concurrently \"cross-env INPUT=index.html vite build\" \"cross-env INPUT=sandbox.html vite build\"", @@ -11,11 +11,11 @@ "dev": "cross-env NODE_ENV=development concurrently \"npm run watch\" \"npm run serve\"" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "react": "^19.2.0", "react-dom": "^19.2.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/express": "^5.0.0", @@ -29,6 +29,7 @@ "prettier": "^3.6.2", "typescript": "^5.9.3", "vite": "^6.0.0", - "vite-plugin-singlefile": "^2.3.0" + "vite-plugin-singlefile": "^2.3.0", + "vitest": "^3.2.4" } } diff --git a/examples/basic-host/src/implementation.ts b/examples/basic-host/src/implementation.ts index 5f680ff..31e3698 100644 --- a/examples/basic-host/src/implementation.ts +++ b/examples/basic-host/src/implementation.ts @@ -1,12 +1,8 @@ import { RESOURCE_MIME_TYPE, getToolUiResourceUri, type McpUiSandboxProxyReadyNotification, AppBridge, PostMessageTransport, type McpUiResourceCsp, type McpUiResourcePermissions, buildAllowAttribute, type McpUiUpdateModelContextRequest, type McpUiMessageRequest } from "@modelcontextprotocol/ext-apps/app-bridge"; -import { - Client, - SSEClientTransport, - StreamableHTTPClientTransport, - type CallToolResult, - type Resource, - type Tool, -} from "@modelcontextprotocol/client"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import type { CallToolResult, Resource, Tool } from "@modelcontextprotocol/sdk/types.js"; import { getTheme, onThemeChange } from "./theme"; import { HOST_STYLE_VARIABLES } from "./host-styles"; diff --git a/examples/basic-host/src/index.tsx b/examples/basic-host/src/index.tsx index 00c0d52..3d488a7 100644 --- a/examples/basic-host/src/index.tsx +++ b/examples/basic-host/src/index.tsx @@ -1,5 +1,5 @@ import { getToolUiResourceUri, McpUiToolMetaSchema } from "@modelcontextprotocol/ext-apps/app-bridge"; -import type { Tool } from "@modelcontextprotocol/client"; +import type { Tool } from "@modelcontextprotocol/sdk/types.js"; import { Component, type ErrorInfo, type ReactNode, StrictMode, Suspense, use, useEffect, useMemo, useRef, useState } from "react"; import { createRoot } from "react-dom/client"; import { callTool, connectToServer, hasAppHtml, initializeApp, loadSandboxProxy, log, newAppBridge, type ServerInfo, type ToolCallInfo, type ModelContext, type AppMessage } from "./implementation"; diff --git a/examples/basic-host/tsconfig.json b/examples/basic-host/tsconfig.json index 3c143ca..9d7c3bc 100644 --- a/examples/basic-host/tsconfig.json +++ b/examples/basic-host/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-preact/main.ts b/examples/basic-server-preact/main.ts index ffdff52..7642632 100644 --- a/examples/basic-server-preact/main.ts +++ b/examples/basic-server-preact/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-preact/package.json b/examples/basic-server-preact/package.json index 60aa40d..a6c0343 100644 --- a/examples/basic-server-preact/package.json +++ b/examples/basic-server-preact/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-preact", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using Preact", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-preact" }, "license": "MIT", @@ -24,15 +24,12 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "preact": "^10.0.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@preact/preset-vite": "^2.0.0", diff --git a/examples/basic-server-preact/server.ts b/examples/basic-server-preact/server.ts index dfec94a..bf14ea5 100644 --- a/examples/basic-server-preact/server.ts +++ b/examples/basic-server-preact/server.ts @@ -1,12 +1,8 @@ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { z } from "zod"; // Works both from source (server.ts) and compiled (dist/server.js) const DIST_DIR = import.meta.filename.endsWith(".ts") ? path.join(import.meta.dirname, "dist") @@ -32,7 +28,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async (): Promise => { diff --git a/examples/basic-server-preact/src/mcp-app.tsx b/examples/basic-server-preact/src/mcp-app.tsx index 351a8ec..a8bdc68 100644 --- a/examples/basic-server-preact/src/mcp-app.tsx +++ b/examples/basic-server-preact/src/mcp-app.tsx @@ -8,7 +8,7 @@ import { applyHostStyleVariables, type McpUiHostContext, } from "@modelcontextprotocol/ext-apps"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { useCallback, useEffect, useState } from "preact/hooks"; import { render } from "preact"; import styles from "./mcp-app.module.css"; diff --git a/examples/basic-server-preact/tsconfig.json b/examples/basic-server-preact/tsconfig.json index 9bf9389..32182d9 100644 --- a/examples/basic-server-preact/tsconfig.json +++ b/examples/basic-server-preact/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-preact/tsconfig.server.json b/examples/basic-server-preact/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-preact/tsconfig.server.json +++ b/examples/basic-server-preact/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/basic-server-react/main.ts b/examples/basic-server-react/main.ts index 21c5e18..ec187b6 100644 --- a/examples/basic-server-react/main.ts +++ b/examples/basic-server-react/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-react/package.json b/examples/basic-server-react/package.json index ea51a8a..f75d662 100644 --- a/examples/basic-server-react/package.json +++ b/examples/basic-server-react/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-react", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using React", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-react" }, "license": "MIT", @@ -34,16 +34,13 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "react": "^19.2.0", "react-dom": "^19.2.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/basic-server-react/server.ts b/examples/basic-server-react/server.ts index d77c908..23f6dda 100644 --- a/examples/basic-server-react/server.ts +++ b/examples/basic-server-react/server.ts @@ -1,12 +1,8 @@ import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; -import { z } from "zod"; // Works both from source (server.ts) and compiled (dist/server.js) const DIST_DIR = import.meta.filename.endsWith(".ts") @@ -33,7 +29,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async (): Promise => { diff --git a/examples/basic-server-react/src/mcp-app.tsx b/examples/basic-server-react/src/mcp-app.tsx index 2b5fbef..6bb5540 100644 --- a/examples/basic-server-react/src/mcp-app.tsx +++ b/examples/basic-server-react/src/mcp-app.tsx @@ -3,7 +3,7 @@ */ import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; import { useApp } from "@modelcontextprotocol/ext-apps/react"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { StrictMode, useCallback, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import styles from "./mcp-app.module.css"; diff --git a/examples/basic-server-react/tsconfig.json b/examples/basic-server-react/tsconfig.json index 3ecbdad..fc3c210 100644 --- a/examples/basic-server-react/tsconfig.json +++ b/examples/basic-server-react/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-react/tsconfig.server.json b/examples/basic-server-react/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-react/tsconfig.server.json +++ b/examples/basic-server-react/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/basic-server-solid/main.ts b/examples/basic-server-solid/main.ts index 095ef8d..c8d9de2 100644 --- a/examples/basic-server-solid/main.ts +++ b/examples/basic-server-solid/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-solid/package.json b/examples/basic-server-solid/package.json index b3ca909..f193fa1 100644 --- a/examples/basic-server-solid/package.json +++ b/examples/basic-server-solid/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-solid", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using Solid", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-solid" }, "license": "MIT", @@ -24,15 +24,12 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "solid-js": "1.9.10", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", @@ -43,7 +40,7 @@ "typescript": "^5.9.3", "vite": "^6.0.0", "vite-plugin-singlefile": "^2.3.0", - "vite-plugin-solid": "^2.11.12" + "vite-plugin-solid": "^2.0.0" }, "types": "dist/server.d.ts", "exports": { diff --git a/examples/basic-server-solid/server.ts b/examples/basic-server-solid/server.ts index addb522..2ed2d93 100644 --- a/examples/basic-server-solid/server.ts +++ b/examples/basic-server-solid/server.ts @@ -1,12 +1,8 @@ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { z } from "zod"; // Works both from source (server.ts) and compiled (dist/server.js) const DIST_DIR = import.meta.filename.endsWith(".ts") ? path.join(import.meta.dirname, "dist") @@ -32,7 +28,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async (): Promise => { diff --git a/examples/basic-server-solid/src/mcp-app.tsx b/examples/basic-server-solid/src/mcp-app.tsx index 2d78b7b..66d47f3 100644 --- a/examples/basic-server-solid/src/mcp-app.tsx +++ b/examples/basic-server-solid/src/mcp-app.tsx @@ -8,7 +8,7 @@ import { applyHostStyleVariables, type McpUiHostContext, } from "@modelcontextprotocol/ext-apps"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { createEffect, createSignal, onMount, Show } from "solid-js"; import { render } from "solid-js/web"; import styles from "./mcp-app.module.css"; diff --git a/examples/basic-server-solid/tsconfig.json b/examples/basic-server-solid/tsconfig.json index bb13a01..84f0efe 100644 --- a/examples/basic-server-solid/tsconfig.json +++ b/examples/basic-server-solid/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-solid/tsconfig.server.json b/examples/basic-server-solid/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-solid/tsconfig.server.json +++ b/examples/basic-server-solid/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/basic-server-svelte/main.ts b/examples/basic-server-svelte/main.ts index 734ec0c..6c50a25 100644 --- a/examples/basic-server-svelte/main.ts +++ b/examples/basic-server-svelte/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-svelte/package.json b/examples/basic-server-svelte/package.json index 19fe4c9..90dd6c6 100644 --- a/examples/basic-server-svelte/package.json +++ b/examples/basic-server-svelte/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-svelte", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using Svelte", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-svelte" }, "license": "MIT", @@ -24,15 +24,12 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "svelte": "^5.0.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^5.0.0", diff --git a/examples/basic-server-svelte/server.ts b/examples/basic-server-svelte/server.ts index 9414285..da603ca 100644 --- a/examples/basic-server-svelte/server.ts +++ b/examples/basic-server-svelte/server.ts @@ -1,12 +1,8 @@ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { z } from "zod"; // Works both from source (server.ts) and compiled (dist/server.js) const DIST_DIR = import.meta.filename.endsWith(".ts") ? path.join(import.meta.dirname, "dist") @@ -32,7 +28,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async (): Promise => { diff --git a/examples/basic-server-svelte/src/App.svelte b/examples/basic-server-svelte/src/App.svelte index cabcc31..fde128d 100644 --- a/examples/basic-server-svelte/src/App.svelte +++ b/examples/basic-server-svelte/src/App.svelte @@ -7,7 +7,7 @@ import { applyHostStyleVariables, type McpUiHostContext, } from "@modelcontextprotocol/ext-apps"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; function extractTime(result: CallToolResult): string { const { text } = result.content?.find((c) => c.type === "text")!; diff --git a/examples/basic-server-svelte/tsconfig.json b/examples/basic-server-svelte/tsconfig.json index 4fd3cd7..5edb66a 100644 --- a/examples/basic-server-svelte/tsconfig.json +++ b/examples/basic-server-svelte/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-svelte/tsconfig.server.json b/examples/basic-server-svelte/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-svelte/tsconfig.server.json +++ b/examples/basic-server-svelte/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/basic-server-vanillajs/main.ts b/examples/basic-server-vanillajs/main.ts index 4de7331..286fa34 100644 --- a/examples/basic-server-vanillajs/main.ts +++ b/examples/basic-server-vanillajs/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-vanillajs/package.json b/examples/basic-server-vanillajs/package.json index ebfebbb..e97eb68 100644 --- a/examples/basic-server-vanillajs/package.json +++ b/examples/basic-server-vanillajs/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-vanillajs", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using vanilla JavaScript", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-vanillajs" }, "license": "MIT", @@ -24,14 +24,11 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/basic-server-vanillajs/server.ts b/examples/basic-server-vanillajs/server.ts index 693d861..5b2daf7 100644 --- a/examples/basic-server-vanillajs/server.ts +++ b/examples/basic-server-vanillajs/server.ts @@ -1,9 +1,6 @@ import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -32,7 +29,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, outputSchema: z.object({ time: z.string(), }), diff --git a/examples/basic-server-vanillajs/src/mcp-app.ts b/examples/basic-server-vanillajs/src/mcp-app.ts index 6b5084a..c3168c2 100644 --- a/examples/basic-server-vanillajs/src/mcp-app.ts +++ b/examples/basic-server-vanillajs/src/mcp-app.ts @@ -8,7 +8,7 @@ import { applyHostStyleVariables, type McpUiHostContext, } from "@modelcontextprotocol/ext-apps"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import "./global.css"; import "./mcp-app.css"; diff --git a/examples/basic-server-vanillajs/tsconfig.json b/examples/basic-server-vanillajs/tsconfig.json index b028ff5..535267b 100644 --- a/examples/basic-server-vanillajs/tsconfig.json +++ b/examples/basic-server-vanillajs/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-vanillajs/tsconfig.server.json b/examples/basic-server-vanillajs/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-vanillajs/tsconfig.server.json +++ b/examples/basic-server-vanillajs/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/basic-server-vue/main.ts b/examples/basic-server-vue/main.ts index d774269..669a071 100644 --- a/examples/basic-server-vue/main.ts +++ b/examples/basic-server-vue/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/basic-server-vue/package.json b/examples/basic-server-vue/package.json index 858dd89..ad8c119 100644 --- a/examples/basic-server-vue/package.json +++ b/examples/basic-server-vue/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-basic-vue", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Basic MCP App Server example using Vue", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/basic-server-vue" }, "license": "MIT", @@ -24,15 +24,12 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "vue": "^3.5.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/basic-server-vue/server.ts b/examples/basic-server-vue/server.ts index 9adb911..5aa72de 100644 --- a/examples/basic-server-vue/server.ts +++ b/examples/basic-server-vue/server.ts @@ -1,12 +1,8 @@ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult, ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { registerAppTool, registerAppResource, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server"; -import { z } from "zod"; // Works both from source (server.ts) and compiled (dist/server.js) const DIST_DIR = import.meta.filename.endsWith(".ts") ? path.join(import.meta.dirname, "dist") @@ -32,7 +28,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time as an ISO 8601 string.", - inputSchema: z.object({}), + inputSchema: {}, _meta: { ui: { resourceUri } }, // Links this tool to its UI resource }, async (): Promise => { diff --git a/examples/basic-server-vue/src/App.vue b/examples/basic-server-vue/src/App.vue index a45c262..196ad64 100644 --- a/examples/basic-server-vue/src/App.vue +++ b/examples/basic-server-vue/src/App.vue @@ -7,7 +7,7 @@ import { applyHostStyleVariables, type McpUiHostContext, } from "@modelcontextprotocol/ext-apps"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; function extractTime(result: CallToolResult): string { const { text } = result.content?.find((c) => c.type === "text")!; diff --git a/examples/basic-server-vue/tsconfig.json b/examples/basic-server-vue/tsconfig.json index 4fd3cd7..5edb66a 100644 --- a/examples/basic-server-vue/tsconfig.json +++ b/examples/basic-server-vue/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/basic-server-vue/tsconfig.server.json b/examples/basic-server-vue/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/basic-server-vue/tsconfig.server.json +++ b/examples/basic-server-vue/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/budget-allocator-server/main.ts b/examples/budget-allocator-server/main.ts index 02c03cb..cc488f0 100644 --- a/examples/budget-allocator-server/main.ts +++ b/examples/budget-allocator-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/budget-allocator-server/package.json b/examples/budget-allocator-server/package.json index 6e41622..71b7ace 100644 --- a/examples/budget-allocator-server/package.json +++ b/examples/budget-allocator-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-budget-allocator", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Budget allocator MCP App Server with interactive visualization", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/budget-allocator-server" }, "license": "MIT", @@ -26,14 +26,12 @@ "serve": "bun --watch main.ts" }, "dependencies": { - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "chart.js": "^4.4.0", "cors": "^2.8.5", "express": "^5.1.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/budget-allocator-server/server.ts b/examples/budget-allocator-server/server.ts index 01f5dbf..e522918 100755 --- a/examples/budget-allocator-server/server.ts +++ b/examples/budget-allocator-server/server.ts @@ -4,11 +4,11 @@ * Provides budget configuration, 24 months of historical allocation data, * and industry benchmarks by company stage. */ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + CallToolResult, + ReadResourceResult, +} from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -269,8 +269,8 @@ export function createServer(): McpServer { { title: "Get Budget Data", description: - "Returns budget configuration with 24 months of historical allocations and industry benchmarks by company stage. The widget is interactive and exposes tools for reading/modifying allocations, adjusting budgets, and comparing against industry benchmarks.", - inputSchema: z.object({}), + "Returns budget configuration with 24 months of historical allocations and industry benchmarks by company stage", + inputSchema: {}, outputSchema: BudgetDataResponseSchema, _meta: { ui: { resourceUri } }, }, diff --git a/examples/budget-allocator-server/src/mcp-app.ts b/examples/budget-allocator-server/src/mcp-app.ts index a9bae12..4e8c62d 100644 --- a/examples/budget-allocator-server/src/mcp-app.ts +++ b/examples/budget-allocator-server/src/mcp-app.ts @@ -3,7 +3,6 @@ */ import { App, type McpUiHostContext } from "@modelcontextprotocol/ext-apps"; import { Chart, registerables } from "chart.js"; -import { z } from "zod"; import "./global.css"; import "./mcp-app.css"; @@ -627,295 +626,6 @@ function handleHostContextChanged(ctx: McpUiHostContext) { app.onhostcontextchanged = handleHostContextChanged; -// Register tools for model interaction -app.registerTool( - "get-allocations", - { - title: "Get Budget Allocations", - description: - "Get the current budget allocations including total budget, percentages, and amounts per category", - }, - async () => { - if (!state.config) { - return { - content: [ - { type: "text" as const, text: "Error: Configuration not loaded" }, - ], - isError: true, - }; - } - - const allocations: Record = {}; - for (const category of state.config.categories) { - const percent = state.allocations.get(category.id) ?? 0; - allocations[category.id] = { - percent, - amount: (percent / 100) * state.totalBudget, - }; - } - - const result = { - totalBudget: state.totalBudget, - currency: state.config.currency, - currencySymbol: state.config.currencySymbol, - selectedStage: state.selectedStage, - allocations, - categories: state.config.categories.map((c) => ({ - id: c.id, - name: c.name, - color: c.color, - })), - }; - - return { - content: [ - { type: "text" as const, text: JSON.stringify(result, null, 2) }, - ], - structuredContent: result, - }; - }, -); - -app.registerTool( - "set-allocation", - { - title: "Set Category Allocation", - description: "Set the allocation percentage for a specific budget category", - inputSchema: z.object({ - categoryId: z - .string() - .describe( - "Category ID (e.g., 'marketing', 'engineering', 'operations', 'sales', 'rd')", - ), - percent: z - .number() - .min(0) - .max(100) - .describe("Allocation percentage (0-100)"), - }), - }, - async (args) => { - if (!state.config) { - return { - content: [ - { type: "text" as const, text: "Error: Configuration not loaded" }, - ], - isError: true, - }; - } - - const category = state.config.categories.find( - (c) => c.id === args.categoryId, - ); - if (!category) { - return { - content: [ - { - type: "text" as const, - text: `Error: Category "${args.categoryId}" not found. Available: ${state.config.categories.map((c) => c.id).join(", ")}`, - }, - ], - isError: true, - }; - } - - handleSliderChange(args.categoryId, args.percent); - - // Also update the slider UI - const slider = document.querySelector( - `.slider-row[data-category-id="${args.categoryId}"] .slider`, - ) as HTMLInputElement | null; - if (slider) { - slider.value = String(args.percent); - } - - const amount = (args.percent / 100) * state.totalBudget; - return { - content: [ - { - type: "text" as const, - text: `Set ${category.name} allocation to ${args.percent.toFixed(1)}% (${state.config.currencySymbol}${amount.toLocaleString()})`, - }, - ], - }; - }, -); - -app.registerTool( - "set-total-budget", - { - title: "Set Total Budget", - description: "Set the total budget amount", - inputSchema: z.object({ - amount: z.number().positive().describe("Total budget amount"), - }), - }, - async (args) => { - if (!state.config) { - return { - content: [ - { type: "text" as const, text: "Error: Configuration not loaded" }, - ], - isError: true, - }; - } - - state.totalBudget = args.amount; - - // Update the budget selector if this amount is a preset - const budgetSelector = document.getElementById( - "budget-selector", - ) as HTMLSelectElement | null; - if (budgetSelector) { - const option = Array.from(budgetSelector.options).find( - (opt) => parseInt(opt.value) === args.amount, - ); - if (option) { - budgetSelector.value = String(args.amount); - } - } - - updateAllSliderAmounts(); - updateStatusBar(); - updateComparisonSummary(); - - return { - content: [ - { - type: "text" as const, - text: `Total budget set to ${state.config.currencySymbol}${args.amount.toLocaleString()}`, - }, - ], - }; - }, -); - -app.registerTool( - "set-company-stage", - { - title: "Set Company Stage", - description: - "Set the company stage for benchmark comparison (e.g., 'Seed', 'Series A', 'Series B', 'Growth')", - inputSchema: z.object({ - stage: z.string().describe("Company stage ID"), - }), - }, - async (args) => { - if (!state.analytics) { - return { - content: [ - { type: "text" as const, text: "Error: Analytics not loaded" }, - ], - isError: true, - }; - } - - if (!state.analytics.stages.includes(args.stage)) { - return { - content: [ - { - type: "text" as const, - text: `Error: Stage "${args.stage}" not found. Available: ${state.analytics.stages.join(", ")}`, - }, - ], - isError: true, - }; - } - - state.selectedStage = args.stage; - - // Update the stage selector UI - const stageSelector = document.getElementById( - "stage-selector", - ) as HTMLSelectElement | null; - if (stageSelector) { - stageSelector.value = args.stage; - } - - // Update all badges and summary - if (state.config) { - for (const category of state.config.categories) { - updatePercentileBadge(category.id); - } - updateComparisonSummary(); - } - - return { - content: [ - { - type: "text" as const, - text: `Company stage set to "${args.stage}"`, - }, - ], - }; - }, -); - -app.registerTool( - "get-benchmark-comparison", - { - title: "Get Benchmark Comparison", - description: - "Compare current allocations against industry benchmarks for the selected stage", - }, - async () => { - if (!state.config || !state.analytics) { - return { - content: [{ type: "text" as const, text: "Error: Data not loaded" }], - isError: true, - }; - } - - const benchmark = state.analytics.benchmarks.find( - (b) => b.stage === state.selectedStage, - ); - if (!benchmark) { - return { - content: [ - { - type: "text" as const, - text: `Error: No benchmark data for stage "${state.selectedStage}"`, - }, - ], - isError: true, - }; - } - - const comparison: Record< - string, - { current: number; p25: number; p50: number; p75: number; status: string } - > = {}; - - for (const category of state.config.categories) { - const current = state.allocations.get(category.id) ?? 0; - const benchmarkData = benchmark.categoryBenchmarks[category.id]; - let status = "within range"; - if (current < benchmarkData.p25) status = "below p25"; - else if (current > benchmarkData.p75) status = "above p75"; - - comparison[category.id] = { - current, - p25: benchmarkData.p25, - p50: benchmarkData.p50, - p75: benchmarkData.p75, - status, - }; - } - - const result = { - stage: state.selectedStage, - comparison, - }; - - return { - content: [ - { type: "text" as const, text: JSON.stringify(result, null, 2) }, - ], - structuredContent: result, - }; - }, -); - // Handle theme changes window .matchMedia("(prefers-color-scheme: dark)") diff --git a/examples/budget-allocator-server/tsconfig.json b/examples/budget-allocator-server/tsconfig.json index b028ff5..535267b 100644 --- a/examples/budget-allocator-server/tsconfig.json +++ b/examples/budget-allocator-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/budget-allocator-server/tsconfig.server.json b/examples/budget-allocator-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/budget-allocator-server/tsconfig.server.json +++ b/examples/budget-allocator-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/cohort-heatmap-server/main.ts b/examples/cohort-heatmap-server/main.ts index 8b33603..d59903b 100644 --- a/examples/cohort-heatmap-server/main.ts +++ b/examples/cohort-heatmap-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/cohort-heatmap-server/package.json b/examples/cohort-heatmap-server/package.json index 7e2d2e2..d753706 100644 --- a/examples/cohort-heatmap-server/package.json +++ b/examples/cohort-heatmap-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-cohort-heatmap", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Cohort heatmap MCP App Server for retention analysis", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/cohort-heatmap-server" }, "license": "MIT", @@ -26,15 +26,13 @@ "serve": "bun --watch main.ts" }, "dependencies": { - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "react": "^19.2.0", "react-dom": "^19.2.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/cohort-heatmap-server/server.ts b/examples/cohort-heatmap-server/server.ts index 129e2dc..6d07144 100644 --- a/examples/cohort-heatmap-server/server.ts +++ b/examples/cohort-heatmap-server/server.ts @@ -1,7 +1,5 @@ -import { - McpServer, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { ReadResourceResult } from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -180,8 +178,8 @@ export function createServer(): McpServer { title: "Get Cohort Retention Data", description: "Returns cohort retention heatmap data showing customer retention over time by signup month", - inputSchema: GetCohortDataInputSchema, - outputSchema: CohortDataSchema, + inputSchema: GetCohortDataInputSchema.shape, + outputSchema: CohortDataSchema.shape, _meta: { ui: { resourceUri } }, }, async ({ metric, periodType, cohortCount, maxPeriods }) => { diff --git a/examples/cohort-heatmap-server/tsconfig.json b/examples/cohort-heatmap-server/tsconfig.json index 3ecbdad..fc3c210 100644 --- a/examples/cohort-heatmap-server/tsconfig.json +++ b/examples/cohort-heatmap-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/cohort-heatmap-server/tsconfig.server.json b/examples/cohort-heatmap-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/cohort-heatmap-server/tsconfig.server.json +++ b/examples/cohort-heatmap-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/customer-segmentation-server/main.ts b/examples/customer-segmentation-server/main.ts index c788757..130076c 100644 --- a/examples/customer-segmentation-server/main.ts +++ b/examples/customer-segmentation-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/customer-segmentation-server/package.json b/examples/customer-segmentation-server/package.json index bac3b89..ade9dae 100644 --- a/examples/customer-segmentation-server/package.json +++ b/examples/customer-segmentation-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-customer-segmentation", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Customer segmentation MCP App Server with filtering", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/customer-segmentation-server" }, "license": "MIT", @@ -26,14 +26,12 @@ "serve": "bun --watch main.ts" }, "dependencies": { - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "chart.js": "^4.4.0", "cors": "^2.8.5", "express": "^5.1.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/customer-segmentation-server/server.ts b/examples/customer-segmentation-server/server.ts index 7cc1c1f..244415d 100644 --- a/examples/customer-segmentation-server/server.ts +++ b/examples/customer-segmentation-server/server.ts @@ -1,8 +1,8 @@ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + CallToolResult, + ReadResourceResult, +} from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -100,8 +100,8 @@ export function createServer(): McpServer { title: "Get Customer Data", description: "Returns customer data with segment information for visualization. Optionally filter by segment.", - inputSchema: GetCustomerDataInputSchema, - outputSchema: GetCustomerDataOutputSchema, + inputSchema: GetCustomerDataInputSchema.shape, + outputSchema: GetCustomerDataOutputSchema.shape, _meta: { ui: { resourceUri } }, }, async ({ segment }): Promise => { diff --git a/examples/customer-segmentation-server/tsconfig.json b/examples/customer-segmentation-server/tsconfig.json index b028ff5..535267b 100644 --- a/examples/customer-segmentation-server/tsconfig.json +++ b/examples/customer-segmentation-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/customer-segmentation-server/tsconfig.server.json b/examples/customer-segmentation-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/customer-segmentation-server/tsconfig.server.json +++ b/examples/customer-segmentation-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/debug-server/main.ts b/examples/debug-server/main.ts index 9fb0825..3c89a97 100644 --- a/examples/debug-server/main.ts +++ b/examples/debug-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/debug-server/package.json b/examples/debug-server/package.json index e28f4d3..15dc903 100644 --- a/examples/debug-server/package.json +++ b/examples/debug-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-debug", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "Debug MCP App Server for testing all SDK capabilities", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/debug-server" }, "license": "MIT", @@ -34,11 +34,9 @@ "prepublishOnly": "npm run build" }, "dependencies": { - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", - "zod": "^4.2.0" + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/debug-server/server.ts b/examples/debug-server/server.ts index 068f94d..fd3452a 100644 --- a/examples/debug-server/server.ts +++ b/examples/debug-server/server.ts @@ -3,11 +3,11 @@ import { registerAppTool, RESOURCE_MIME_TYPE, } from "@modelcontextprotocol/ext-apps/server"; -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + CallToolResult, + ReadResourceResult, +} from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import { appendFileSync } from "node:fs"; import path from "node:path"; diff --git a/examples/debug-server/tsconfig.json b/examples/debug-server/tsconfig.json index b028ff5..535267b 100644 --- a/examples/debug-server/tsconfig.json +++ b/examples/debug-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/debug-server/tsconfig.server.json b/examples/debug-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/debug-server/tsconfig.server.json +++ b/examples/debug-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/integration-server/main.ts b/examples/integration-server/main.ts index 9a42842..c45787e 100644 --- a/examples/integration-server/main.ts +++ b/examples/integration-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/integration-server/package.json b/examples/integration-server/package.json index 7e04f4a..5686a02 100644 --- a/examples/integration-server/package.json +++ b/examples/integration-server/package.json @@ -1,6 +1,6 @@ { "name": "integration-server", - "version": "2.0.0", + "version": "1.4.0", "private": true, "type": "module", "scripts": { @@ -15,16 +15,13 @@ "serve": "bun --watch main.ts" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", "react": "^19.2.0", "react-dom": "^19.2.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/integration-server/server.ts b/examples/integration-server/server.ts index 346f4f7..e44689d 100644 --- a/examples/integration-server/server.ts +++ b/examples/integration-server/server.ts @@ -3,11 +3,11 @@ import { registerAppTool, RESOURCE_MIME_TYPE, } from "@modelcontextprotocol/ext-apps/server"; -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + CallToolResult, + ReadResourceResult, +} from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -33,7 +33,7 @@ export function createServer(): McpServer { { title: "Get Time", description: "Returns the current server time.", - inputSchema: z.object({}), + inputSchema: {}, outputSchema: z.object({ time: z.string(), }), @@ -72,7 +72,7 @@ export function createServer(): McpServer { ); // Sample downloadable resource — used to demo ResourceLink in ui/download-file - server.registerResource( + server.resource( SAMPLE_DOWNLOAD_URI, SAMPLE_DOWNLOAD_URI, { diff --git a/examples/integration-server/src/mcp-app.tsx b/examples/integration-server/src/mcp-app.tsx index 281a356..7f0b18c 100644 --- a/examples/integration-server/src/mcp-app.tsx +++ b/examples/integration-server/src/mcp-app.tsx @@ -3,7 +3,7 @@ */ import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; import { useApp } from "@modelcontextprotocol/ext-apps/react"; -import type { CallToolResult } from "@modelcontextprotocol/client"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { StrictMode, useCallback, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import styles from "./mcp-app.module.css"; diff --git a/examples/integration-server/tsconfig.json b/examples/integration-server/tsconfig.json index 3ecbdad..fc3c210 100644 --- a/examples/integration-server/tsconfig.json +++ b/examples/integration-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/integration-server/tsconfig.server.json b/examples/integration-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/integration-server/tsconfig.server.json +++ b/examples/integration-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/lazy-auth-server/README.md b/examples/lazy-auth-server/README.md deleted file mode 100644 index f2e7545..0000000 --- a/examples/lazy-auth-server/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# Example: Lazy Auth Server - -An MCP App example demonstrating **lazy (on-demand) auth**: the server connects and lists tools without any authentication, and only asks for OAuth when a _protected_ tool is actually called — by answering `401` with a `WWW-Authenticate` header. A public MCP App renders an "Auth me" button; clicking it calls a protected tool via [`callServerTool`](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html#callservertool). The host sees the 401, runs the OAuth flow, retries, and the result renders inline. - -The embedded OAuth authorization server is a deliberately minimal mock (HS256 JWTs, stateless auth codes, auto-approve consent page) so the whole flow runs from a single process with no external dependencies. It is **not** a production authorization server. - -## Tools - -| Tool | Auth | Description | -| ------------------- | ------------- | ----------------------------------------------------------------------------------------------------- | -| `show_auth_button` | public | Renders buttons: "Auth me" (calls `get_secret`), "Revoke token" (calls `revoke_auth_token`) | -| `get_secret` | **protected** | Returns secret data (requires Bearer token) | -| `revoke_auth_token` | **protected** | Revokes the caller's **entire auth session** (access + refresh token) → forces full re-auth | -| `elicit_url` | public | URL elicitation via `elicitInput` (blocks until the elicitation completes) | -| `elicit_by_error` | public | URL elicitation via the `-32042` (`UrlElicitationRequired`) error; succeeds on retry after completion | - -## Getting Started - -```bash -npm install -npm start -# → MCP endpoint at http://localhost:3097/mcp -``` - -To test with a remote MCP host, expose the server through a public tunnel (see [Testing MCP Apps](../../docs/testing-mcp-apps.md)) and set `PUBLIC_URL` to the tunnel URL so OAuth metadata and callback URLs use it: - -```bash -PUBLIC_URL=https:// npm start -``` - -This example is HTTP-only (no stdio mode): the lazy-auth flow relies on HTTP status codes and OAuth endpoints. - -## Environment Variables - -| Var | Required | Description | -| --------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `JWT_SECRET` | recommended | 32+ byte secret for HS256 signing (`openssl rand -hex 32`). A dev-only default is used if unset. | -| `PORT` | no | Local port (default 3097) | -| `PUBLIC_URL` | non-local | Public base URL of the server (e.g. your tunnel URL). Required for non-localhost deployments; client-supplied `Host` headers are only trusted for loopback hosts | -| `ACCESS_TOKEN_TTL_SECONDS` | no | Default access-token lifetime (default **30**, short on purpose so you can watch the host's refresh flow kick in) | -| `REFRESH_TOKEN_TTL_SECONDS` | no | Default refresh-token lifetime (default **300**). Between the access and refresh TTLs, calls succeed via silent refresh; past it, a full re-auth is required | -| `REACTIVE_AUTH_ONLY` | no | Set `1` to remove auth metadata from the root `/.well-known/oauth-*` paths so hosts can't discover auth preemptively — discovery then only happens via the 401 | - -### Per-connection token lifetimes - -The short defaults are great for watching the refresh flow, but slow or automated clients may want tokens that survive a whole session. Any client can request a different access-token lifetime by connecting to a TTL-scoped MCP endpoint path (capped at 24 hours): - -``` -https:///ttl/3600/mcp ← tokens for this connection live 1 hour -``` - -This works through [RFC 8707 resource indicators](https://www.rfc-editor.org/rfc/rfc8707): MCP hosts send the MCP server URL as the `resource` parameter in OAuth authorization and token requests, and this server issues tokens for that grant with the lifetime encoded in the path (refresh tokens are extended to at least match). The TTL is a _path_ segment rather than a query param because hosts canonicalize resource indicators and strip query strings. Each TTL endpoint also enforces its value as a maximum token age, so connecting to a path with a _lower_ TTL than a token's issued lifetime forces the refresh flow. To exercise the full **re-auth** flow, call the `revoke_auth_token` tool. - -## Mounting under a base path - -`createApp()` can also be mounted inside another Express app, so an existing server can host this example at a sub-path of its own origin: - -```ts -import { createApp } from "@modelcontextprotocol/server-lazy-auth"; - -hostApp.use("/lazy-auth", createApp()); -// → MCP endpoint at https:///lazy-auth/mcp -``` - -All advertised URLs (OAuth metadata, `WWW-Authenticate` `resource_metadata`, PRM `resource`, elicitation callbacks) include the mount path automatically, derived from Express's `req.baseUrl`. When `PUBLIC_URL` is set, it must include the mount path (e.g. `https://example.com/lazy-auth`). - -One thing the mounted app cannot do for itself: [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414#section-3) / [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) put well-known discovery documents at the _root_ of the origin with the path inserted after the well-known prefix (`/.well-known/oauth-authorization-server/lazy-auth`), and MCP SDK clients only try that insertion form. The host app must rewrite those root paths into the mount before its other routes: - -```ts -hostApp.use((req, _res, next) => { - const m = req.url.match( - /^\/\.well-known\/(oauth-authorization-server|oauth-protected-resource)\/lazy-auth(\/.*)?$/, - ); - if (m) req.url = `/lazy-auth/.well-known/${m[1]}${m[2] ?? ""}`; - next(); -}); -``` - -Rewriting into the mount (rather than calling the sub-app directly) keeps `req.baseUrl` — and therefore every advertised URL — consistent. - -## How It Works - -1. **Connect without auth** — `initialize`, `tools/list`, and public tool calls succeed with no `Authorization` header. -2. **Protected tool → 401** — when `get_secret` or `revoke_auth_token` is called without a (valid) Bearer token, the server responds `401` with `WWW-Authenticate: Bearer resource_metadata="…/auth/prm"`. -3. **Discovery** — the host follows `resource_metadata` to the protected-resource metadata (RFC 9728), which points at the authorization server metadata (RFC 8414). -4. **OAuth flow** — the host runs the authorization-code + PKCE flow against the mock `/authorize` and `/token` endpoints (a small consent page keeps the popup visible). -5. **Retry** — the host retries the tool call with the Bearer token and the secret renders inline in the app. -6. **Refresh + revocation** — access tokens expire after 30 seconds and refresh tokens after 5 minutes by default, so all three states are easy to observe: direct success (<30s), silent refresh (30s–5min), and full re-auth (>5min). Connections can request different lifetimes via the `/ttl//mcp` endpoint path (see [Per-connection token lifetimes](#per-connection-token-lifetimes)), and `revoke_auth_token` invalidates the whole session immediately. - -The two `elicit_*` tools demonstrate the complementary pattern of [URL elicitation](https://modelcontextprotocol.io/specification/draft/client/elicitation), where the server asks the user to open a URL (e.g. to complete sign-in) either by blocking inside the tool call (`elicit_url`) or by failing with the `-32042` error and succeeding on retry (`elicit_by_error`). - -## Architecture - -- **Stateless auth codes** — grant details are encoded _inside_ the authorization code as a 5-minute JWT, so nothing needs to be stored between requests. -- **Short-lived tokens** — access tokens default to a **30 second** TTL and refresh tokens to **5 minutes**: first `get_secret` succeeds → wait >30s → next call 401s → host refreshes → retry succeeds → wait >5min → full re-auth. Per-connection overrides via the `/ttl//mcp` endpoint path. -- **HS256** — a single shared secret; no key-pair persistence. -- **Per-request MCP server** — each `/mcp` request gets a fresh `McpServer` + `StreamableHTTPServerTransport` (stateless, no session IDs). -- **Session revocation** — all tokens from one OAuth session share a `sid` claim; `revoke_auth_token` adds the sid to an in-memory revocation list checked by both token verification and the refresh grant. - -## Key Files - -- [`server.ts`](server.ts) - OAuth endpoints, discovery metadata, and the MCP server with public + protected tools -- [`main.ts`](main.ts) - HTTP entry point -- [`mcp-app.html`](mcp-app.html) / [`src/mcp-app.ts`](src/mcp-app.ts) - Public app with the "Auth me" button -- [`secret-app.html`](secret-app.html) / [`src/secret-app.ts`](src/secret-app.ts) - Protected app rendered for `get_secret` diff --git a/examples/lazy-auth-server/main.ts b/examples/lazy-auth-server/main.ts deleted file mode 100644 index a96f34c..0000000 --- a/examples/lazy-auth-server/main.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Entry point for running the Lazy Auth demo MCP server. - * Run with: npx mcp-server-lazy-auth - * Or: node dist/index.js - * - * This example is HTTP-only (no stdio mode): the lazy-auth flow it demonstrates - * relies on HTTP status codes (401 + WWW-Authenticate) and OAuth endpoints. - * - * To test with a remote MCP host, expose the server through a public tunnel - * and set PUBLIC_URL to the tunnel URL so OAuth metadata and callback URLs - * use it (see docs/testing-mcp-apps.md in the repository root). - */ -import { createApp, PORT } from "./server.js"; - -async function main() { - const app = createApp(); - - const httpServer = app.listen(PORT, (err) => { - if (err) { - console.error("Failed to start server:", err); - process.exit(1); - } - console.log( - `Lazy Auth demo MCP server listening on http://localhost:${PORT}/mcp`, - ); - console.log( - ` Tools: show_auth_button, get_secret [PROTECTED], revoke_auth_token [PROTECTED], elicit_url, elicit_by_error`, - ); - }); - - const shutdown = () => { - console.log("\nShutting down..."); - httpServer.close(() => process.exit(0)); - }; - process.on("SIGINT", shutdown); - process.on("SIGTERM", shutdown); -} - -main().catch((e) => { - console.error(e); - process.exit(1); -}); diff --git a/examples/lazy-auth-server/mcp-app.html b/examples/lazy-auth-server/mcp-app.html deleted file mode 100644 index 7040f15..0000000 --- a/examples/lazy-auth-server/mcp-app.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - Lazy Auth Demo - - -
-

Public App

-

- No auth was needed to render this view. Click below to invoke the - protected - get_secret tool — the host will run the OAuth flow on 401 - and retry. -

-
- - - -
-
-
- - - diff --git a/examples/lazy-auth-server/package.json b/examples/lazy-auth-server/package.json deleted file mode 100644 index dbd4601..0000000 --- a/examples/lazy-auth-server/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "@modelcontextprotocol/server-lazy-auth", - "version": "2.0.0", - "type": "module", - "description": "MCP App example demonstrating lazy (on-demand) OAuth: public tools work unauthenticated, protected tools return 401 + WWW-Authenticate so the host runs the OAuth flow only when needed", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", - "directory": "examples/lazy-auth-server" - }, - "license": "MIT", - "main": "dist/server.js", - "files": [ - "dist" - ], - "scripts": { - "build": "tsc --noEmit && cross-env INPUT=mcp-app.html vite build && cross-env INPUT=secret-app.html vite build && tsc -p tsconfig.server.json && bun build server.ts --outdir dist --target node && bun build main.ts --outfile dist/index.js --target node --external \"./server.js\" --banner \"#!/usr/bin/env node\"", - "watch": "concurrently \"cross-env INPUT=mcp-app.html vite build --watch\" \"cross-env INPUT=secret-app.html vite build --watch\"", - "serve": "bun --watch main.ts", - "start": "cross-env NODE_ENV=development npm run build && npm run serve", - "dev": "cross-env NODE_ENV=development concurrently \"npm run watch\" \"npm run serve\"", - "prepublishOnly": "npm run build" - }, - "dependencies": { - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", - "cors": "^2.8.5", - "express": "^5.1.0", - "jose": "^6.0.0", - "zod": "^4.2.0" - }, - "devDependencies": { - "@types/cors": "^2.8.19", - "@types/express": "^5.0.0", - "@types/node": "22.10.0", - "concurrently": "^9.2.1", - "cross-env": "^10.1.0", - "typescript": "^5.9.3", - "vite": "^6.0.0", - "vite-plugin-singlefile": "^2.3.0" - }, - "types": "dist/server.d.ts", - "exports": { - ".": { - "types": "./dist/server.d.ts", - "default": "./dist/server.js" - } - }, - "bin": { - "mcp-server-lazy-auth": "dist/index.js" - } -} diff --git a/examples/lazy-auth-server/secret-app.html b/examples/lazy-auth-server/secret-app.html deleted file mode 100644 index b2ab00b..0000000 --- a/examples/lazy-auth-server/secret-app.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - Lazy Auth Demo — Secret - - -
-

Protected App

-
Waiting for secret data…
-
- - - diff --git a/examples/lazy-auth-server/server.ts b/examples/lazy-auth-server/server.ts deleted file mode 100644 index 5240008..0000000 --- a/examples/lazy-auth-server/server.ts +++ /dev/null @@ -1,1134 +0,0 @@ -/** - * Lazy Auth demo MCP server. - * - * Demonstrates "lazy" (on-demand) OAuth for MCP servers and Apps: - * - * - The server connects without authentication: `initialize`, `tools/list`, - * and public tool calls all succeed with no Bearer token. - * - Protected tools (`get_secret`, `revoke_auth_token`) return 401 with a - * `WWW-Authenticate` header pointing at protected-resource metadata, so the - * host only runs the OAuth flow when a protected tool is actually called. - * - The `show_auth_button` MCP App is public; clicking its button calls the - * protected `get_secret` tool via `callServerTool`. The host sees the 401, - * runs OAuth, retries, and the result renders inline. - * - * The embedded OAuth authorization server is intentionally minimal and - * stateless (HS256 JWTs, auth codes encoded as short-lived JWTs) so the demo - * can run anywhere with a single env var. It is NOT a production AS. - */ -import { - registerAppResource, - registerAppTool, - RESOURCE_MIME_TYPE, -} from "@modelcontextprotocol/ext-apps/server"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import { - McpServer, - UrlElicitationRequiredError, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; -import cors from "cors"; -import express, { type Express, type Request, type Response } from "express"; -import { SignJWT, jwtVerify } from "jose"; -import crypto from "node:crypto"; -import fs from "node:fs/promises"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { z } from "zod"; - -// Works both from source (server.ts) and compiled (dist/server.js). Derived -// from import.meta.url rather than import.meta.filename/dirname, which are -// undefined in some module-VM contexts (e.g. importing this package from -// jest). -const SERVER_FILE = fileURLToPath(import.meta.url); -const DIST_DIR = SERVER_FILE.endsWith(".ts") - ? path.join(path.dirname(SERVER_FILE), "dist") - : path.dirname(SERVER_FILE); - -// ─── Config ────────────────────────────────────────────────────────────────── - -export const PORT = parseInt(process.env.PORT ?? "3097", 10); -const JWT_SECRET = new TextEncoder().encode( - process.env.JWT_SECRET ?? - "dev-insecure-secret-do-not-use-in-production-" + "x".repeat(20), -); -const PROTECTED_TOOLS = new Set(["get_secret", "revoke_auth_token"]); -// Token lifetimes. Defaults are deliberately short so the host's refresh flow -// (30s–5min after auth) and full re-auth (>5min) are easy to observe in a demo. -// Slow or automated clients can request longer-lived tokens per connection by -// connecting to a TTL-scoped endpoint path (/ttl//mcp) — see -// ttlFromResource() and the README. -const ACCESS_TOKEN_TTL_SECONDS = parseInt( - process.env.ACCESS_TOKEN_TTL_SECONDS ?? "30", - 10, -); -const REFRESH_TOKEN_TTL_SECONDS = parseInt( - process.env.REFRESH_TOKEN_TTL_SECONDS ?? "300", - 10, -); -// Cap on per-connection `?token_ttl_s=` requests. -const MAX_TOKEN_TTL_SECONDS = 86400; -// When true: root well-known PRM returns *stub* metadata WITHOUT authorization_servers, -// and root well-known AS is 404. Hosts probing well-known on connect see "resource has -// PRM but no auth configured" → connect without OAuth. Real PRM (with authorization_servers) -// is only at /auth/prm, reachable via WWW-Authenticate on 401. Default false = standard. -const REACTIVE_AUTH_ONLY = process.env.REACTIVE_AUTH_ONLY === "1"; - -/** Hostname is localhost / a loopback address (URL-style, so IPv6 keeps its brackets). */ -function isLoopbackHostname(hostname: string): boolean { - return ( - ["localhost", "127.0.0.1", "[::1]"].includes(hostname) || - hostname.endsWith(".localhost") - ); -} - -/** - * Resolve the public base URL for this deployment. - * - * Precedence: the PUBLIC_URL env var, then the request's Host header (loopback - * hosts only), then http://localhost:PORT. Host / X-Forwarded-* headers naming - * non-loopback hosts are deliberately NOT trusted — a client could spoof them - * to make OAuth metadata and callback URLs point at a host it controls. - * Non-localhost deployments (e.g. behind a public tunnel) must set PUBLIC_URL - * explicitly. - */ -function resolvePublicUrl(req?: Request): URL { - // Mount path when this app is mounted inside another Express app - // (e.g. app.use("/lazy-auth", createApp())). Empty when standalone. - // PUBLIC_URL, when set, must already include any mount path. - const basePath = req?.baseUrl ?? ""; - const envUrl = process.env.PUBLIC_URL; - if (envUrl) return new URL(envUrl.endsWith("/") ? envUrl : envUrl + "/"); - const host = req?.headers.host; - if (host) { - try { - const url = new URL(`http://${host}${basePath}/`); - if (isLoopbackHostname(url.hostname)) return url; - } catch { - // Malformed Host header → fall through to the localhost default. - } - } - return new URL(`http://localhost:${PORT}${basePath}/`); -} - -/** Public base URL as a string with no trailing slash (may include a base path). */ -function publicBaseHref(req?: Request): string { - const href = resolvePublicUrl(req).href; - return href.endsWith("/") ? href.slice(0, -1) : href; -} - -/** OAuth issuer. In REACTIVE_AUTH_ONLY mode, uses a /auth subpath so root well-known 404s. - * Otherwise uses the public base URL (origin + any mount path). */ -const ISSUER_SUFFIX = REACTIVE_AUTH_ONLY ? "/auth" : ""; -function resolveIssuer(req?: Request): string { - return publicBaseHref(req) + ISSUER_SUFFIX; -} - -// ─── Mock OAuth (HS256, stateless codes) ───────────────────────────────────── - -interface CodePayload { - client_id: string; - redirect_uri: string; - code_challenge?: string; - code_challenge_method?: string; - scope?: string; - /** Requested access-token TTL, from `?token_ttl_s=` on the resource indicator. */ - token_ttl_s?: number; -} - -/** Validate + cap a raw TTL value (from a path segment or query param). */ -function parseTtlSeconds(raw: string | undefined): number | undefined { - const ttl = parseInt(raw ?? "", 10); - return Number.isFinite(ttl) && ttl > 0 - ? Math.min(ttl, MAX_TOKEN_TTL_SECONDS) - : undefined; -} - -/** - * Extract the requested access-token TTL from a resource indicator (RFC 8707). - * - * MCP hosts send `resource=` — the URL the client connected - * to — in authorization and token requests. Clients opt into a non-default - * token lifetime by connecting to a TTL-scoped MCP endpoint path: - * - * /ttl//mcp (e.g. /ttl/3600/mcp for 1-hour tokens) - * - * The TTL lives in the PATH because hosts canonicalize resource indicators and - * strip query strings (verified against real hosts), so `?token_ttl_s=` query - * params would never reach this server's OAuth endpoints. The query param is - * still honored as a fallback for clients that preserve it. - */ -function ttlFromResource(resource: string | undefined): number | undefined { - if (!resource) return undefined; - try { - const url = new URL(resource); - const pathMatch = url.pathname.match(/\/ttl\/(\d+)\/mcp$/); - return ( - parseTtlSeconds(pathMatch?.[1]) ?? - parseTtlSeconds(url.searchParams.get("token_ttl_s") ?? undefined) - ); - } catch { - return undefined; - } -} - -interface AuthInfo { - token: string; - sub: string; - sid: string; -} - -// ─── Session revocation ─────────────────────────────────────────────────────── -// -// Each OAuth session (authorize → code → tokens) gets a single `sid`; all access & -// refresh tokens in that session carry it. Revoking the sid invalidates both → host -// must do a full re-OAuth (refresh grant also fails). -// -// Storage is an in-memory Map, which is fine for a single-process demo server. If -// you deploy this to a multi-instance/serverless environment, back it with a -// shared store instead. - -const revokedSids = new Map(); // sid → unix GC time -// Revoked-sid entries need only outlive the longest token TTL; add small clock-skew grace. -const REVOCATION_GC_TTL_SECONDS = - Math.max( - ACCESS_TOKEN_TTL_SECONDS, - REFRESH_TOKEN_TTL_SECONDS, - MAX_TOKEN_TTL_SECONDS, - ) + 10; - -function revokeSession(sid: string): void { - revokedSids.set( - sid, - Math.floor(Date.now() / 1000) + REVOCATION_GC_TTL_SECONDS, - ); - const now = Math.floor(Date.now() / 1000); - for (const [k, gc] of revokedSids) if (gc < now) revokedSids.delete(k); -} - -function isSessionRevoked(sid: string | undefined): boolean { - if (!sid) return false; - return revokedSids.has(sid); -} - -async function signAccessToken( - sub: string, - scope: string, - sid: string, - issuer: string, - audience: string, - ttlSeconds: number = ACCESS_TOKEN_TTL_SECONDS, -): Promise { - return new SignJWT({ sub, scope, sid }) - .setProtectedHeader({ alg: "HS256" }) - .setIssuedAt() - .setIssuer(issuer) - .setAudience(audience) - .setExpirationTime(`${ttlSeconds}s`) - .sign(JWT_SECRET); -} - -async function signRefreshToken( - sub: string, - scope: string, - sid: string, - issuer: string, - ttlSeconds: number = REFRESH_TOKEN_TTL_SECONDS, - accessTtlSeconds?: number, -): Promise { - // access_ttl_s carries the grant's requested access-token TTL forward so - // refreshed access tokens keep the same lifetime as the original. - return new SignJWT({ - sub, - scope, - sid, - typ: "refresh", - ...(accessTtlSeconds !== undefined - ? { access_ttl_s: accessTtlSeconds } - : {}), - }) - .setProtectedHeader({ alg: "HS256" }) - .setIssuedAt() - .setIssuer(issuer) - .setExpirationTime(`${ttlSeconds}s`) - .sign(JWT_SECRET); -} - -async function verifyRefreshToken( - token: string, - issuer: string, -): Promise< - | { sub: string; scope: string; sid: string; accessTtlSeconds?: number } - | undefined -> { - try { - const { payload } = await jwtVerify(token, JWT_SECRET, { issuer }); - if (payload.typ !== "refresh") return undefined; - const sid = payload.sid as string | undefined; - if (isSessionRevoked(sid)) return undefined; // session revoked → refresh fails - return { - sub: payload.sub ?? "", - scope: (payload.scope as string) ?? "", - sid: sid ?? "", - accessTtlSeconds: - typeof payload.access_ttl_s === "number" - ? payload.access_ttl_s - : undefined, - }; - } catch { - return undefined; - } -} - -/** Encode grant details inside the code itself (5min expiry) — no server storage. */ -async function signAuthCode( - payload: CodePayload, - issuer: string, -): Promise { - return new SignJWT({ ...payload, typ: "code" }) - .setProtectedHeader({ alg: "HS256" }) - .setIssuedAt() - .setJti(crypto.randomUUID()) - .setIssuer(issuer) - .setExpirationTime("5m") - .sign(JWT_SECRET); -} - -// Authorization codes are single-use (RFC 6749 §4.1.2): remember redeemed code -// IDs until the code's own 5-minute expiry makes replay impossible anyway. -const redeemedCodeJtis = new Map(); // jti → unix GC time - -async function verifyAuthCode( - code: string, - issuer: string, -): Promise { - try { - const { payload } = await jwtVerify(code, JWT_SECRET, { issuer }); - if (payload.typ !== "code" || !payload.jti) return undefined; - const now = Math.floor(Date.now() / 1000); - for (const [k, gc] of redeemedCodeJtis) - if (gc < now) redeemedCodeJtis.delete(k); - if (redeemedCodeJtis.has(payload.jti)) return undefined; // already redeemed - redeemedCodeJtis.set(payload.jti, now + 5 * 60 + 10); - return payload as unknown as CodePayload; - } catch { - return undefined; - } -} - -async function verifyAccessToken( - token: string, - issuer: string, - maxAgeSeconds?: number, -): Promise { - try { - const { payload } = await jwtVerify(token, JWT_SECRET, { issuer }); - if (payload.typ === "code" || payload.typ === "refresh") return undefined; // only plain access tokens - const sid = payload.sid as string | undefined; - if (isSessionRevoked(sid)) return undefined; // session revoked - // Per-connection TTL override (?token_ttl_s= on the MCP URL): treat tokens - // older than maxAgeSeconds as expired even though their exp claim is still - // in the future. Lets one deployment serve both long-TTL (default) and - // short-TTL (refresh-flow testing) connections. - if (maxAgeSeconds !== undefined && typeof payload.iat === "number") { - const ageSeconds = Math.floor(Date.now() / 1000) - payload.iat; - if (ageSeconds > maxAgeSeconds) return undefined; - } - return { token, sub: payload.sub ?? "", sid: sid ?? "" }; - } catch { - return undefined; - } -} - -function escapeHtml(s: string) { - return s.replace( - /[&<>"']/g, - (c) => - ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ - c - ]!, - ); -} - -/** - * This demo AS has no client registry, so it can't check redirect URIs against - * pre-registered values. At minimum, only allow https targets (or http on - * loopback for local development hosts) so the consent page never links to, - * or redirects the authorization code to, an unexpected scheme. - */ -function isAllowedRedirectUri(redirectUri: string): boolean { - try { - const url = new URL(redirectUri); - if (url.protocol === "https:") return true; - return url.protocol === "http:" && isLoopbackHostname(url.hostname); - } catch { - return false; - } -} - -async function handleAuthorize(req: Request, res: Response) { - const { - client_id, - redirect_uri, - state, - code_challenge, - code_challenge_method, - scope, - approved, - resource, - } = req.query as Record; - if (!redirect_uri) { - res.status(400).json({ - error: "invalid_request", - error_description: "Missing redirect_uri", - }); - return; - } - if (!isAllowedRedirectUri(redirect_uri)) { - res.status(400).json({ - error: "invalid_request", - error_description: "redirect_uri must use https (or http on localhost)", - }); - return; - } - // PKCE is mandatory (the MCP auth spec requires it of clients, and this AS - // only advertises S256). Rejecting up front keeps stolen-code attacks out of - // the demo even though it has no real data to protect. - if (!code_challenge || code_challenge_method !== "S256") { - res.status(400).json({ - error: "invalid_request", - error_description: "PKCE with S256 code_challenge is required", - }); - return; - } - const issuer = resolveIssuer(req); - - if (approved !== "1") { - // Show consent page. Keeps the OAuth popup visible so users can see the flow. - const approveUrl = new URL(publicBaseHref(req) + "/authorize"); - for (const [k, v] of Object.entries(req.query)) - if (v) approveUrl.searchParams.set(k, String(v)); - approveUrl.searchParams.set("approved", "1"); - const denyUrl = new URL(redirect_uri); - denyUrl.searchParams.set("error", "access_denied"); - if (state) denyUrl.searchParams.set("state", state); - res.type("text/html").send(/*html*/ ` -Authorize - - -
-

🔑 Mock Authorization

-

An application is requesting access:

-
Client
${escapeHtml(client_id ?? "(none)")}
-
Scope
${escapeHtml(scope ?? "(default)")}
-
Redirect
${escapeHtml(redirect_uri)}
- -
- -`); - return; - } - - // Per-grant token TTL, requested via `?token_ttl_s=` on the resource - // indicator (the MCP URL the host is authorizing for). Encoded into the - // auth code so /token can issue tokens with the requested lifetime. - const tokenTtl = ttlFromResource(resource); - const code = await signAuthCode( - { - client_id, - redirect_uri, - code_challenge, - code_challenge_method, - scope, - ...(tokenTtl !== undefined ? { token_ttl_s: tokenTtl } : {}), - }, - issuer, - ); - const redirectUrl = new URL(redirect_uri); - redirectUrl.searchParams.set("code", code); - if (state) redirectUrl.searchParams.set("state", state); - console.log( - `[auth] issued code for client_id=${client_id}` + - (tokenTtl !== undefined ? ` (token_ttl_s=${tokenTtl})` : ""), - ); - res.redirect(redirectUrl.href); -} - -async function handleToken(req: Request, res: Response) { - const { grant_type, code, code_verifier, refresh_token, resource } = req.body; - const issuer = resolveIssuer(req); - const audience = resolvePublicUrl(req).href; - - if (grant_type === "refresh_token") { - const refreshClaims = await verifyRefreshToken(refresh_token, issuer); - if (!refreshClaims) { - console.log(`[auth] refresh rejected (invalid/revoked)`); - res.status(400).json({ - error: "invalid_grant", - error_description: "Refresh token invalid or revoked", - }); - return; - } - // Refreshed access tokens keep the grant's requested TTL: prefer the - // resource indicator on this request, else the TTL carried in the refresh - // token, else the default. - const accessTtl = - ttlFromResource(resource) ?? - refreshClaims.accessTtlSeconds ?? - ACCESS_TOKEN_TTL_SECONDS; - const access_token = await signAccessToken( - refreshClaims.sub, - refreshClaims.scope, - refreshClaims.sid, - issuer, - audience, - accessTtl, - ); - console.log( - `[auth] refreshed access token (sid=${refreshClaims.sid}, ttl=${accessTtl}s)`, - ); - res.json({ - access_token, - token_type: "Bearer", - expires_in: accessTtl, - scope: refreshClaims.scope, - refresh_token, - }); - return; - } - if (grant_type !== "authorization_code") { - res.status(400).json({ error: "unsupported_grant_type" }); - return; - } - const stored = await verifyAuthCode(code, issuer); - if (!stored) { - res.status(400).json({ - error: "invalid_grant", - error_description: "Invalid or expired code", - }); - return; - } - // PKCE verification (challenges are always present — /authorize requires them). - if (!code_verifier) { - res.status(400).json({ - error: "invalid_grant", - error_description: "Missing code_verifier", - }); - return; - } - const hash = crypto - .createHash("sha256") - .update(code_verifier) - .digest("base64url"); - if (hash !== stored.code_challenge) { - res.status(400).json({ - error: "invalid_grant", - error_description: "PKCE verification failed", - }); - return; - } - // RFC 6749 §4.1.3 redirect_uri binding: if the client includes redirect_uri - // in the token request it must match the one from the authorization request. - // (OAuth 2.1 clients may omit it and rely on PKCE, which is enforced above.) - if (req.body.redirect_uri && req.body.redirect_uri !== stored.redirect_uri) { - res.status(400).json({ - error: "invalid_grant", - error_description: "redirect_uri does not match authorization request", - }); - return; - } - const scope = stored.scope ?? "read:secret"; - const sid = crypto.randomBytes(16).toString("hex"); // new session per authorization_code grant - // Per-grant TTL: prefer the resource indicator on this request (RFC 8707), - // else the TTL encoded in the auth code at /authorize, else the default. - // Refresh tokens must outlive the access tokens they can mint. - const accessTtl = - ttlFromResource(resource) ?? stored.token_ttl_s ?? ACCESS_TOKEN_TTL_SECONDS; - const refreshTtl = Math.max(REFRESH_TOKEN_TTL_SECONDS, accessTtl); - const access_token = await signAccessToken( - "mock-user-123", - scope, - sid, - issuer, - audience, - accessTtl, - ); - const refresh = await signRefreshToken( - "mock-user-123", - scope, - sid, - issuer, - refreshTtl, - accessTtl, - ); - console.log( - `[auth] exchanged code → token (client_id=${stored.client_id}, scope=${scope}, sid=${sid}, access_ttl=${accessTtl}s, refresh_ttl=${refreshTtl}s)`, - ); - res.json({ - access_token, - token_type: "Bearer", - expires_in: accessTtl, - scope, - refresh_token: refresh, - }); -} - -// ─── Elicitation state (module-level — survives across SHTTP requests) ────── -// -// Streamable HTTP creates a fresh McpServer per request, so state must live at -// module scope. This is fine for a single-process demo server; back it with a -// shared store if you deploy multiple instances. - -/** elicitationIds the user has completed via /elicitation-callback */ -const completedElicitations = new Set(); -/** elicit_by_error: remember the last-issued eid so retries can check it */ -let lastIssuedElicitationId: string | undefined; - -// ─── MCP Server ────────────────────────────────────────────────────────────── - -/** - * Creates a new MCP server instance with tools and resources registered. - * - * @param authInfo - Verified Bearer token info, if the request carried one. - * @param req - The inbound HTTP request (used to resolve the public URL). - */ -export function createServer(authInfo?: AuthInfo, req?: Request): McpServer { - const server = new McpServer({ name: "Lazy Auth Demo", version: "1.0.0" }); - - const buttonUri = "ui://lazy-auth/mcp-app.html"; - registerAppTool( - server, - "show_auth_button", - { - title: "Show Auth Button", - description: - "Public tool: shows a button that triggers the protected get_secret tool.", - inputSchema: z.object({}), - _meta: { ui: { resourceUri: buttonUri } }, - }, - async (): Promise => ({ - content: [{ type: "text", text: "ok" }], - }), - ); - registerAppResource( - server, - buttonUri, - buttonUri, - { mimeType: RESOURCE_MIME_TYPE }, - async (): Promise => { - const html = await fs.readFile( - path.join(DIST_DIR, "mcp-app.html"), - "utf-8", - ); - return { - contents: [ - { uri: buttonUri, mimeType: RESOURCE_MIME_TYPE, text: html }, - ], - }; - }, - ); - - const secretUri = "ui://lazy-auth/secret-app.html"; - registerAppTool( - server, - "get_secret", - { - title: "Get Secret", - description: - "Protected tool: returns secret data. Requires authentication.", - inputSchema: z.object({}), - _meta: { ui: { resourceUri: secretUri } }, - }, - async (): Promise => { - if (!authInfo) { - return { - isError: true, - content: [{ type: "text", text: "Authentication required." }], - }; - } - const secret = { - subject: authInfo.sub, - secret: "the-answer-is-42", - issuedAt: new Date().toISOString(), - }; - return { - content: [{ type: "text", text: JSON.stringify(secret, null, 2) }], - }; - }, - ); - registerAppResource( - server, - secretUri, - secretUri, - { mimeType: RESOURCE_MIME_TYPE }, - async (): Promise => { - const html = await fs.readFile( - path.join(DIST_DIR, "secret-app.html"), - "utf-8", - ); - return { - contents: [ - { uri: secretUri, mimeType: RESOURCE_MIME_TYPE, text: html }, - ], - }; - }, - ); - - server.registerTool( - "revoke_auth_token", - { - title: "Revoke Auth Token", - description: - "Protected tool: revokes the caller's entire auth session (access + refresh token).", - inputSchema: z.object({}), - }, - async (): Promise => { - if (!authInfo) { - return { - isError: true, - content: [{ type: "text", text: "Authentication required." }], - }; - } - revokeSession(authInfo.sid); - console.log( - `[auth] revoked session sid=${authInfo.sid} (total revoked sessions: ${revokedSids.size})`, - ); - return { - content: [ - { - type: "text", - text: `Session revoked (sid: ${authInfo.sid}). Access + refresh token invalid → full re-auth required.`, - }, - ], - }; - }, - ); - - // ── Elicitation test tools ──────────────────────────────────────────────── - // Public tools — no auth. Used to exercise a host's URL-elicitation flow - // end-to-end over Streamable HTTP. - - const base = publicBaseHref(req); - const callbackUrl = (eid: string) => - `${base}/elicitation-callback?id=${encodeURIComponent(eid)}`; - - server.registerTool( - "elicit_url", - { - title: "Elicit URL (session-callback)", - description: - "URL elicitation via elicitInput. Blocks until the client accepts; sends ElicitCompleteNotification before returning.", - inputSchema: z.object({}), - }, - async (_args, extra): Promise => { - const eid = crypto.randomUUID(); - // Defer notifier creation — checks client capabilities which throws if - // client doesn't advertise elicitation. Create lazily after elicitInput - // succeeds (implies client supports it). - console.log(`[elicit_url] eid=${eid} — blocking on elicitInput`); - const result = await server.server.elicitInput( - { - mode: "url", - url: callbackUrl(eid), - message: "Please open this URL to continue.", - elicitationId: eid, - }, - { relatedRequestId: extra.mcpReq.id, timeout: 300_000 }, - ); - // Send completion notification before returning — lands on the same SSE - // stream as this tool response. For Streamable HTTP this is the ONLY - // window where the server can push a notification (stream closes right - // after). The notification is optional per spec — skip if the client - // doesn't support it. - try { - const notifier = server.server.createElicitationCompletionNotifier(eid); - await notifier(); - console.log( - `[elicit_url] eid=${eid} — notified, result=${result.action}`, - ); - } catch (e) { - console.log( - `[elicit_url] eid=${eid} — notify skipped: ${e instanceof Error ? e.message : e}, result=${result.action}`, - ); - } - return { - content: [ - { type: "text", text: `elicit_url: ${JSON.stringify(result)}` }, - ], - }; - }, - ); - - server.registerTool( - "elicit_by_error", - { - title: "Elicit by -32042 Error", - description: - "Throws UrlElicitationRequiredError (-32042). Client must open the URL, then retry. On retry, if the last-issued elicitationId was completed, sends ElicitCompleteNotification and succeeds.", - inputSchema: z.object({}), - }, - async (): Promise => { - // Retry path: check if the user completed the elicitation we last issued. - // Module-level state survives across Streamable HTTP requests in a single - // process. Checking ANY completed eid (not just last-issued) would be more - // forgiving, but last-issued is the stricter real-world pattern hosts must - // handle. - if ( - lastIssuedElicitationId && - completedElicitations.has(lastIssuedElicitationId) - ) { - const eid = lastIssuedElicitationId; - completedElicitations.delete(eid); - lastIssuedElicitationId = undefined; - // Send notification DURING this (retry) tool call — only window where - // the Streamable HTTP stream is open. The notification is optional per - // spec — createElicitationCompletionNotifier throws if the client - // doesn't advertise the capability, but the tool still succeeds. - try { - const notifier = - server.server.createElicitationCompletionNotifier(eid); - await notifier(); - console.log( - `[elicit_by_error] eid=${eid} — completed on retry, notified`, - ); - } catch (e) { - console.log( - `[elicit_by_error] eid=${eid} — completed on retry, notify skipped: ${e instanceof Error ? e.message : e}`, - ); - } - return { - content: [ - { - type: "text", - text: `Auth completed (${eid}). Tool succeeded on retry.`, - }, - ], - }; - } - const eid = crypto.randomUUID(); - lastIssuedElicitationId = eid; - console.log(`[elicit_by_error] eid=${eid} — throwing -32042`); - throw new UrlElicitationRequiredError([ - { - mode: "url", - url: callbackUrl(eid), - message: - "This tool requires authentication. Please open the link to continue.", - elicitationId: eid, - }, - ]); - }, - ); - - return server; -} - -// ─── Express app ───────────────────────────────────────────────────────────── - -/** - * Creates the Express app: OAuth endpoints, discovery metadata, and the /mcp - * endpoint with lazy (401-triggered) auth on protected tools. - */ -export function createApp(): Express { - const app = express(); - // Wildcard CORS is deliberate: browser-based MCP hosts connect to this demo - // from arbitrary origins and must read WWW-Authenticate to drive the lazy - // auth flow. There are no cookies or ambient credentials to protect — all - // auth is an explicit Bearer header, and /token is a credential-less PKCE - // exchange — so cross-origin reads expose nothing a direct request wouldn't. - app.use(cors({ exposedHeaders: ["WWW-Authenticate"] })); - app.use(express.json()); - app.use(express.urlencoded({ extended: true })); - - // Request tracing: log every inbound request (incl. query params) so we can - // see what hosts probe during connect and what they send through OAuth. - app.use((req, _res, next) => { - const ua = (req.headers["user-agent"] ?? "").slice(0, 80); - const auth = req.headers.authorization ? "[Bearer]" : "[no-auth]"; - const query = Object.keys(req.query).length - ? ` query=${JSON.stringify(req.query)}` - : ""; - console.log(`[req] ${req.method} ${req.path} ${auth}${query} ua=${ua}`); - next(); - }); - - // OAuth endpoints - app.get("/authorize", handleAuthorize); - app.post("/token", handleToken); - - // OAuth discovery metadata. In REACTIVE_AUTH_ONLY mode, PRM + AS are kept off the - // ROOT /.well-known paths so MCP hosts can't proactively probe them and trigger - // preemptive auth during connection — discovery is purely reactive: - // 401 → WWW-Authenticate → PRM → AS → OAuth flow. - const PRM_PATH = "/auth/prm"; - - function buildAsMetadata(req: Request) { - const base = publicBaseHref(req); - return { - issuer: resolveIssuer(req), // subpath issuer → well-known at /.well-known/.../auth - authorization_endpoint: `${base}/authorize`, - token_endpoint: `${base}/token`, - response_types_supported: ["code"], - grant_types_supported: ["authorization_code", "refresh_token"], - code_challenge_methods_supported: ["S256"], - token_endpoint_auth_methods_supported: ["none"], - scopes_supported: ["read:secret"], - client_id_metadata_document_supported: true, - }; - } - - // AS metadata: serve at the issuer's well-known location. - // - REACTIVE_AUTH_ONLY: only at /.well-known/.../auth (subpath); root 404s. - // - Default: also at root /.well-known/... (standard; some hosts probe this on connect). - if (ISSUER_SUFFIX) { - // Per RFC 8414 §3: issuer /auth → /.well-known/oauth-authorization-server/auth - app.get( - `/.well-known/oauth-authorization-server${ISSUER_SUFFIX}`, - (req, res) => res.json(buildAsMetadata(req)), - ); - // RFC 8615 style (well-known between host and path): - app.get( - `${ISSUER_SUFFIX}/.well-known/oauth-authorization-server`, - (req, res) => res.json(buildAsMetadata(req)), - ); - } - if (!REACTIVE_AUTH_ONLY) { - // Default mode: full AS metadata at root well-known (standard). - app.get("/.well-known/oauth-authorization-server", (req, res) => - res.json(buildAsMetadata(req)), - ); - } - - // PRM: full version at custom path (referenced via WWW-Authenticate on 401). - function buildPrm(req: Request, includeAuth: boolean, resourcePath = "/mcp") { - const base = publicBaseHref(req); - return { - resource: `${base}${resourcePath}`, - ...(includeAuth - ? { - authorization_servers: [resolveIssuer(req)], - scopes_supported: ["read:secret"], - bearer_methods_supported: ["header"], - } - : {}), - }; - } - /** Resource path for a TTL-scoped MCP endpoint, validating the TTL segment. */ - function ttlResourcePath(rawTtl: string): string | undefined { - const ttl = parseTtlSeconds(rawTtl); - return ttl !== undefined ? `/ttl/${ttl}/mcp` : undefined; - } - app.get(PRM_PATH, (req, res) => res.json(buildPrm(req, true))); - app.get(`${PRM_PATH}/ttl/:ttl`, (req, res) => { - const resourcePath = ttlResourcePath(String(req.params.ttl)); - if (!resourcePath) { - res.status(404).json({ error: "invalid_ttl" }); - return; - } - res.json(buildPrm(req, true, resourcePath)); - }); - // Root + path-dependent well-known PRM: in REACTIVE mode these 404 so hosts don't - // interpret their presence as "server has OAuth". In default mode, full PRM. - if (!REACTIVE_AUTH_ONLY) { - app.get("/.well-known/oauth-protected-resource", (req, res) => - res.json(buildPrm(req, true)), - ); - app.get("/.well-known/oauth-protected-resource/mcp", (req, res) => - res.json(buildPrm(req, true)), - ); - // Well-known PRM for TTL-scoped MCP endpoints (RFC 9728 derives this URL - // from the resource path, so each TTL path has its own). - app.get( - "/.well-known/oauth-protected-resource/ttl/:ttl/mcp", - (req, res) => { - const resourcePath = ttlResourcePath(String(req.params.ttl)); - if (!resourcePath) { - res.status(404).json({ error: "invalid_ttl" }); - return; - } - res.json(buildPrm(req, true, resourcePath)); - }, - ); - } - - // /register: some MCP hosts fall through to OAuth dynamic client registration (RFC 7591) - // when all well-known probes 404. We don't support it — return a proper OAuth error so - // the host concludes "auth not available here" and connects without OAuth, instead of - // treating a generic 404 as a connection failure. - app.post("/register", (_req, res) => { - res.status(400).json({ - error: "invalid_request", - error_description: - "Dynamic client registration is not supported. This server uses per-tool auth triggered via WWW-Authenticate on 401.", - }); - }); - - // MCP endpoint handler, shared by the default and TTL-scoped paths. - // pathTtl (from /ttl//mcp) doubles as the acceptance window for - // Bearer tokens: tokens older than it are rejected even if their issued - // lifetime was longer. - async function handleMcp( - req: Request, - res: Response, - pathTtl: number | undefined, - ) { - const base = publicBaseHref(req); - const resourceMetadataUrl = - pathTtl !== undefined - ? `${base}${PRM_PATH}/ttl/${pathTtl}` - : `${base}${PRM_PATH}`; - - const body = req.body; - const messages = Array.isArray(body) ? body : body ? [body] : []; - const needsAuth = messages.some( - (msg: { method?: string; params?: { name?: string } }) => - msg?.method === "tools/call" && - PROTECTED_TOOLS.has(msg.params?.name ?? ""), - ); - - // Acceptance window: the path TTL, else the `?token_ttl_s=` query param - // (fallback for clients that preserve query strings). - const tokenMaxAgeSeconds = - pathTtl ?? parseTtlSeconds(String(req.query.token_ttl_s ?? "")); - - let authInfo: AuthInfo | undefined; - const authHeader = req.headers.authorization; - if (authHeader?.startsWith("Bearer ")) { - authInfo = await verifyAccessToken( - authHeader.slice(7), - resolveIssuer(req), - tokenMaxAgeSeconds, - ); - if (!authInfo && needsAuth) { - console.log(`[mcp] 401: invalid token for protected tool`); - res - .status(401) - .set( - "WWW-Authenticate", - `Bearer error="invalid_token", error_description="The access token is invalid", resource_metadata="${resourceMetadataUrl}"`, - ) - .json({ - error: "invalid_token", - error_description: "The access token is invalid", - }); - return; - } - } else if (needsAuth) { - console.log(`[mcp] 401: no token for protected tool`); - res - .status(401) - .set( - "WWW-Authenticate", - `Bearer resource_metadata="${resourceMetadataUrl}"`, - ) - .json({ - error: "invalid_token", - error_description: "Authorization required", - }); - return; - } - - const server = createServer(authInfo, req); - const transport = new NodeStreamableHTTPServerTransport({ - sessionIdGenerator: undefined, - }); - res.on("close", () => { - transport.close().catch(() => {}); - server.close().catch(() => {}); - }); - - try { - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - } catch (error) { - console.error("[mcp] Error:", error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: "2.0", - error: { code: -32603, message: "Internal server error" }, - id: null, - }); - } - } - } - - // Default MCP endpoint (default token TTLs). - app.all("/mcp", (req: Request, res: Response) => - handleMcp(req, res, undefined), - ); - // TTL-scoped MCP endpoint: tokens for connections made through this path are - // issued with (and limited to) the requested lifetime, e.g. /ttl/3600/mcp. - app.all("/ttl/:ttl/mcp", (req: Request, res: Response) => { - const pathTtl = parseTtlSeconds(String(req.params.ttl)); - if (pathTtl === undefined) { - res.status(404).json({ error: "invalid_ttl" }); - return; - } - return handleMcp(req, res, pathTtl); - }); - - // Elicitation callback — marks an eid as completed. Module-level state; - // the next elicit_by_error retry reads it. Minimal confirmation page so - // the popup shows something. - app.get("/elicitation-callback", (req, res) => { - const id = String(req.query.id ?? ""); - if (!id) { - res.status(400).type("text/plain").send("missing ?id="); - return; - } - completedElicitations.add(id); - console.log( - `[callback] eid=${id} completed (total: ${completedElicitations.size})`, - ); - res - .type("text/html") - .send( - `Done` + - `` + - `

✓ Elicitation completed

` + - `

${escapeHtml(id)}

` + - `

You can close this tab. The tool will succeed on the next retry.

`, - ); - }); - - // Simple landing page - app.get("/", (req, res) => { - const base = publicBaseHref(req); - res - .type("text/plain") - .send( - `Lazy Auth Demo — MCP server\n\n` + - ` MCP endpoint: ${base}/mcp\n` + - ` ${base}/ttl//mcp (custom token TTL, e.g. /ttl/3600/mcp)\n` + - ` AS metadata: ${base}/.well-known/oauth-authorization-server${ISSUER_SUFFIX}\n` + - ` PRM metadata: ${base}${PRM_PATH}\n\n` + - `Tools:\n` + - ` - show_auth_button (public)\n` + - ` - get_secret (protected, requires Bearer token)\n` + - ` - revoke_auth_token (protected, revokes caller's auth session)\n` + - ` - elicit_url (public, URL elicitation via elicitInput)\n` + - ` - elicit_by_error (public, URL elicitation via -32042 error)\n`, - ); - }); - - return app; -} diff --git a/examples/lazy-auth-server/src/global.css b/examples/lazy-auth-server/src/global.css deleted file mode 100644 index 54a9860..0000000 --- a/examples/lazy-auth-server/src/global.css +++ /dev/null @@ -1,100 +0,0 @@ -:root { - color-scheme: light dark; - - /* - * Fallbacks for host style variables used by this app. - * The host may provide these (and many more) via the host context. - */ - --color-text-primary: light-dark(#1f2937, #f3f4f6); - --color-text-inverse: light-dark(#f3f4f6, #1f2937); - --color-text-info: light-dark(#1d4ed8, #60a5fa); - --color-background-primary: light-dark(#ffffff, #1a1a1a); - --color-background-inverse: light-dark(#1a1a1a, #ffffff); - --color-background-info: light-dark(#eff6ff, #1e3a5f); - --color-ring-primary: light-dark(#3b82f6, #60a5fa); - --border-radius-md: 6px; - --border-width-regular: 1px; - --font-sans: - ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", - "Segoe UI Symbol", "Noto Color Emoji"; - --font-mono: - ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", - "Courier New", monospace; - --font-weight-normal: 400; - --font-weight-bold: 700; - --font-text-md-size: 1rem; - --font-text-md-line-height: 1.5; - --font-heading-3xl-size: 2.25rem; - --font-heading-3xl-line-height: 1.1; - --font-heading-2xl-size: 1.875rem; - --font-heading-2xl-line-height: 1.2; - --font-heading-xl-size: 1.5rem; - --font-heading-xl-line-height: 1.25; - --font-heading-lg-size: 1.25rem; - --font-heading-lg-line-height: 1.3; - --font-heading-md-size: 1rem; - --font-heading-md-line-height: 1.4; - --font-heading-sm-size: 0.875rem; - --font-heading-sm-line-height: 1.4; - - /* Spacing derived from host typography */ - --spacing-unit: var(--font-text-md-size); - --spacing-xs: calc(var(--spacing-unit) * 0.25); - --spacing-sm: calc(var(--spacing-unit) * 0.5); - --spacing-md: var(--spacing-unit); - --spacing-lg: calc(var(--spacing-unit) * 1.5); - - /* App accent color (customize for your brand) */ - --color-accent: #2563eb; - --color-text-on-accent: #ffffff; -} - -* { - box-sizing: border-box; -} - -html, -body { - font-family: var(--font-sans); - font-size: var(--font-text-md-size); - font-weight: var(--font-weight-normal); - line-height: var(--font-text-md-line-height); - color: var(--color-text-primary); -} - -h1 { - font-size: var(--font-heading-3xl-size); - line-height: var(--font-heading-3xl-line-height); -} -h2 { - font-size: var(--font-heading-2xl-size); - line-height: var(--font-heading-2xl-line-height); -} -h3 { - font-size: var(--font-heading-xl-size); - line-height: var(--font-heading-xl-line-height); -} -h4 { - font-size: var(--font-heading-lg-size); - line-height: var(--font-heading-lg-line-height); -} -h5 { - font-size: var(--font-heading-md-size); - line-height: var(--font-heading-md-line-height); -} -h6 { - font-size: var(--font-heading-sm-size); - line-height: var(--font-heading-sm-line-height); -} - -code, -pre, -kbd { - font-family: var(--font-mono); - font-size: 1em; -} - -b, -strong { - font-weight: var(--font-weight-bold); -} diff --git a/examples/lazy-auth-server/src/mcp-app.css b/examples/lazy-auth-server/src/mcp-app.css deleted file mode 100644 index 800b224..0000000 --- a/examples/lazy-auth-server/src/mcp-app.css +++ /dev/null @@ -1,82 +0,0 @@ -.main { - width: 100%; - max-width: 480px; - box-sizing: border-box; - - > * { - margin-top: 0; - margin-bottom: 0; - } - - > * + * { - margin-top: var(--spacing-md); - } -} - -.actions { - display: flex; - flex-wrap: wrap; - gap: var(--spacing-sm); - /* Keep a long press on or near the buttons from starting text selection - or raising the iOS callout menu instead of a click. */ - -webkit-user-select: none; - user-select: none; - -webkit-touch-callout: none; -} - -button { - /* Match the consent page's 56px tap targets (server.ts .btn). */ - min-height: 56px; - min-width: 56px; - padding: var(--spacing-sm) var(--spacing-md); - border: none; - border-radius: var(--border-radius-md); - color: var(--color-text-on-accent); - font-weight: var(--font-weight-bold); - background-color: var(--color-accent); - cursor: pointer; - /* Suppress the double-tap-to-zoom gesture so a tap resolves to a click - immediately instead of waiting to see if a second tap follows. */ - touch-action: manipulation; - -webkit-tap-highlight-color: transparent; - - &:disabled { - opacity: 0.5; - cursor: not-allowed; - } - - &:active:not(:disabled) { - filter: brightness(0.85); - } - - &:hover:not(:disabled) { - background-color: color-mix( - in srgb, - var(--color-accent) 85%, - var(--color-background-inverse) - ); - } - - &:focus-visible { - outline: calc(var(--border-width-regular) * 2) solid - var(--color-ring-primary); - outline-offset: var(--border-width-regular); - } -} - -.result { - padding: var(--spacing-sm) var(--spacing-md); - border: var(--border-width-regular) solid - color-mix(in srgb, var(--color-text-primary) 25%, transparent); - border-radius: var(--border-radius-md); - font-family: var(--font-mono); - font-size: 0.875em; - white-space: pre-wrap; - word-break: break-word; -} - -.error { - color: var(--color-text-danger, light-dark(#b91c1c, #f87171)); - white-space: pre-wrap; - word-break: break-word; -} diff --git a/examples/lazy-auth-server/src/mcp-app.ts b/examples/lazy-auth-server/src/mcp-app.ts deleted file mode 100644 index f959d71..0000000 --- a/examples/lazy-auth-server/src/mcp-app.ts +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file Public app view: buttons that call the protected tools. - * - * The view itself renders without auth. Clicking "Auth me" calls the protected - * `get_secret` tool via `callServerTool`; the host receives a 401 from the - * server, runs the OAuth flow, retries the call, and the result renders here. - */ -import { - App, - applyDocumentTheme, - applyHostFonts, - applyHostStyleVariables, - type McpUiHostContext, -} from "@modelcontextprotocol/ext-apps"; -import "./global.css"; -import "./mcp-app.css"; - -const mainEl = document.querySelector(".main") as HTMLElement; -const authBtn = document.getElementById("auth-btn") as HTMLButtonElement; -const revokeBtn = document.getElementById("revoke-btn") as HTMLButtonElement; -const fullscreenBtn = document.getElementById( - "fullscreen-btn", -) as HTMLButtonElement; -const outputEl = document.getElementById("output")!; - -function handleHostContextChanged(ctx: McpUiHostContext) { - if (ctx.theme) { - applyDocumentTheme(ctx.theme); - } - if (ctx.styles?.variables) { - applyHostStyleVariables(ctx.styles.variables); - } - if (ctx.styles?.css?.fonts) { - applyHostFonts(ctx.styles.css.fonts); - } - if (ctx.safeAreaInsets) { - mainEl.style.paddingTop = `${ctx.safeAreaInsets.top}px`; - mainEl.style.paddingRight = `${ctx.safeAreaInsets.right}px`; - mainEl.style.paddingBottom = `${ctx.safeAreaInsets.bottom}px`; - mainEl.style.paddingLeft = `${ctx.safeAreaInsets.left}px`; - } -} - -const app = new App( - { name: "Lazy Auth Demo", version: "1.0.0" }, - { availableDisplayModes: ["inline", "fullscreen"] }, -); - -// The host echoes the result of the originating `show_auth_button` call; nothing to render. -app.ontoolresult = () => {}; -app.onerror = console.error; -app.onhostcontextchanged = handleHostContextChanged; - -function renderOutput(text: string, isError: boolean) { - const div = document.createElement("div"); - div.className = isError ? "error" : "result"; - div.textContent = text; - outputEl.replaceChildren(div); -} - -/** - * Calls a (protected) server tool. The interesting part happens on the host: - * the server answers 401 + WWW-Authenticate, the host runs the OAuth flow, - * then retries the call and returns the result here. - * - * The default MCP request timeout is 60s; the OAuth flow involves a human - * approving a consent page, which can easily take longer. Use a generous - * timeout so the pending call survives the sign-in round trip. - */ -const AUTH_FLOW_TIMEOUT_MS = 5 * 60_000; - -async function callTool(name: string) { - outputEl.replaceChildren(); - try { - console.info(`Calling ${name} tool...`); - const result = await app.callServerTool( - { name, arguments: {} }, - { timeout: AUTH_FLOW_TIMEOUT_MS }, - ); - const text = - result.content?.find((c) => c.type === "text")?.text ?? "(no content)"; - renderOutput(text, result.isError === true); - } catch (e) { - renderOutput(String(e instanceof Error ? e.message : e), true); - } -} - -authBtn.addEventListener("click", async () => { - authBtn.disabled = true; - try { - await callTool("get_secret"); - } finally { - authBtn.disabled = false; - } -}); - -revokeBtn.addEventListener("click", async () => { - revokeBtn.disabled = true; - try { - await callTool("revoke_auth_token"); - } finally { - revokeBtn.disabled = false; - } -}); - -let displayMode = "inline"; -fullscreenBtn.addEventListener("click", async () => { - fullscreenBtn.disabled = true; - try { - const next = displayMode === "fullscreen" ? "inline" : "fullscreen"; - const { mode } = await app.requestDisplayMode({ mode: next }); - displayMode = mode; - } catch (e) { - console.warn("Display mode not supported:", e); - } finally { - fullscreenBtn.disabled = false; - } -}); - -app.connect().then(() => { - const ctx = app.getHostContext(); - if (ctx) { - handleHostContextChanged(ctx); - displayMode = ctx.displayMode ?? "inline"; - } -}); diff --git a/examples/lazy-auth-server/src/secret-app.ts b/examples/lazy-auth-server/src/secret-app.ts deleted file mode 100644 index aeb6857..0000000 --- a/examples/lazy-auth-server/src/secret-app.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file Protected app view: renders the result of the `get_secret` tool. - * - * This view is only reached after the host has completed the OAuth flow - * (the tool call that produces it requires a Bearer token). - */ -import { - App, - applyDocumentTheme, - applyHostFonts, - applyHostStyleVariables, - type McpUiHostContext, -} from "@modelcontextprotocol/ext-apps"; -import "./global.css"; -import "./mcp-app.css"; - -const mainEl = document.querySelector(".main") as HTMLElement; -const outputEl = document.getElementById("output")!; - -function handleHostContextChanged(ctx: McpUiHostContext) { - if (ctx.theme) { - applyDocumentTheme(ctx.theme); - } - if (ctx.styles?.variables) { - applyHostStyleVariables(ctx.styles.variables); - } - if (ctx.styles?.css?.fonts) { - applyHostFonts(ctx.styles.css.fonts); - } - if (ctx.safeAreaInsets) { - mainEl.style.paddingTop = `${ctx.safeAreaInsets.top}px`; - mainEl.style.paddingRight = `${ctx.safeAreaInsets.right}px`; - mainEl.style.paddingBottom = `${ctx.safeAreaInsets.bottom}px`; - mainEl.style.paddingLeft = `${ctx.safeAreaInsets.left}px`; - } -} - -const app = new App({ name: "Lazy Auth Demo (Secret)", version: "1.0.0" }); - -app.onerror = console.error; -app.onhostcontextchanged = handleHostContextChanged; - -app.ontoolresult = (result) => { - const text = - result.content?.find((c) => c.type === "text")?.text ?? "(no content)"; - const div = document.createElement("div"); - div.className = result.isError ? "error" : "result"; - div.textContent = text; - outputEl.replaceChildren(div); -}; - -app.connect().then(() => { - const ctx = app.getHostContext(); - if (ctx) { - handleHostContextChanged(ctx); - } -}); diff --git a/examples/lazy-auth-server/tsconfig.json b/examples/lazy-auth-server/tsconfig.json deleted file mode 100644 index d6a42ce..0000000 --- a/examples/lazy-auth-server/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "types": ["node", "vite/client"], - "target": "ESNext", - "lib": ["ESNext", "DOM", "DOM.Iterable"], - "module": "ESNext", - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "verbatimModuleSyntax": true, - "noEmit": true, - "strict": true, - "skipLibCheck": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true - }, - "include": ["src", "server.ts", "main.ts"] -} diff --git a/examples/lazy-auth-server/tsconfig.server.json b/examples/lazy-auth-server/tsconfig.server.json deleted file mode 100644 index 27eb28f..0000000 --- a/examples/lazy-auth-server/tsconfig.server.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "types": ["node"], - "target": "ES2022", - "lib": ["ES2022"], - "module": "NodeNext", - "moduleResolution": "NodeNext", - "declaration": true, - "emitDeclarationOnly": true, - "outDir": "./dist", - "rootDir": ".", - "strict": true, - "skipLibCheck": true, - "esModuleInterop": true, - "resolveJsonModule": true - }, - "include": ["server.ts"] -} diff --git a/examples/lazy-auth-server/vite.config.ts b/examples/lazy-auth-server/vite.config.ts deleted file mode 100644 index 6ff6d99..0000000 --- a/examples/lazy-auth-server/vite.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig } from "vite"; -import { viteSingleFile } from "vite-plugin-singlefile"; - -const INPUT = process.env.INPUT; -if (!INPUT) { - throw new Error("INPUT environment variable is not set"); -} - -const isDevelopment = process.env.NODE_ENV === "development"; - -export default defineConfig({ - plugins: [viteSingleFile()], - build: { - sourcemap: isDevelopment ? "inline" : undefined, - cssMinify: !isDevelopment, - minify: !isDevelopment, - - rollupOptions: { - input: INPUT, - }, - outDir: "dist", - emptyOutDir: false, - }, -}); diff --git a/examples/map-server/README.md b/examples/map-server/README.md index e1e044a..4c4de5f 100644 --- a/examples/map-server/README.md +++ b/examples/map-server/README.md @@ -122,7 +122,7 @@ Vanilla TypeScript app that: - [`server.ts`](server.ts) - MCP server with geocode and show-map tools - [`mcp-app.html`](mcp-app.html) / [`src/mcp-app.ts`](src/mcp-app.ts) - CesiumJS globe UI -- [`main.ts`](main.ts) - HTTP and stdio server utilities +- [`server-utils.ts`](server-utils.ts) - HTTP server utilities ## Notes diff --git a/examples/map-server/main.ts b/examples/map-server/main.ts index 8038394..f91f57b 100644 --- a/examples/map-server/main.ts +++ b/examples/map-server/main.ts @@ -4,10 +4,10 @@ * Or: node dist/index.js [--stdio] */ -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { createServer } from "./server.js"; @@ -27,7 +27,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/map-server/package.json b/examples/map-server/package.json index cc4585f..a8d727b 100644 --- a/examples/map-server/package.json +++ b/examples/map-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-map", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "MCP App Server example with CesiumJS 3D globe and geocoding", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/map-server" }, "license": "MIT", @@ -26,14 +26,11 @@ "serve": "bun --watch main.ts" }, "dependencies": { - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/map-server/server.ts b/examples/map-server/server.ts index 5767d46..540d35c 100644 --- a/examples/map-server/server.ts +++ b/examples/map-server/server.ts @@ -5,11 +5,11 @@ * - geocode: Search for places using OpenStreetMap Nominatim * - show-map: Display an interactive 3D globe at a given location */ -import { - McpServer, - type CallToolResult, - type ReadResourceResult, -} from "@modelcontextprotocol/server"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + CallToolResult, + ReadResourceResult, +} from "@modelcontextprotocol/sdk/types.js"; import fs from "node:fs/promises"; import path from "node:path"; import { z } from "zod"; @@ -147,8 +147,8 @@ export function createServer(): McpServer { { title: "Show Map", description: - "Display an interactive world map zoomed to a specific bounding box. Use the GeoCode tool to find the bounding box of a location. The widget is interactive and exposes tools for navigation (fly to locations) and querying the current view.", - inputSchema: z.object({ + "Display an interactive world map zoomed to a specific bounding box. Use the GeoCode tool to find the bounding box of a location.", + inputSchema: { west: z .number() .optional() @@ -173,7 +173,7 @@ export function createServer(): McpServer { .string() .optional() .describe("Optional label to display on the map"), - }), + }, _meta: { ui: { resourceUri } }, }, async ({ west, south, east, north, label }): Promise => ({ @@ -196,13 +196,13 @@ export function createServer(): McpServer { title: "Geocode", description: "Search for places using OpenStreetMap. Returns coordinates and bounding boxes for up to 5 matches.", - inputSchema: z.object({ + inputSchema: { query: z .string() .describe( "Place name or address to search for (e.g., 'Paris', 'Golden Gate Bridge', '1600 Pennsylvania Ave')", ), - }), + }, }, async ({ query }): Promise => { try { diff --git a/examples/map-server/src/mcp-app.ts b/examples/map-server/src/mcp-app.ts index d3090c7..4fda132 100644 --- a/examples/map-server/src/mcp-app.ts +++ b/examples/map-server/src/mcp-app.ts @@ -6,8 +6,7 @@ * a navigate-to tool for the host to control navigation. */ import { App } from "@modelcontextprotocol/ext-apps"; -import type { ContentBlock } from "@modelcontextprotocol/client"; -import { z } from "zod"; +import type { ContentBlock } from "@modelcontextprotocol/sdk/spec.types.js"; // TypeScript declaration for Cesium loaded from CDN // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -560,76 +559,6 @@ function setViewToBoundingBox(cesiumViewer: any, bbox: BoundingBox): void { ); } -/** - * Fly camera to view a bounding box with animation - */ -function flyToBoundingBox( - cesiumViewer: any, - bbox: BoundingBox, - duration = 2, -): Promise { - return new Promise((resolve) => { - const { destination, centerLon, centerLat, height } = - calculateDestination(bbox); - - log.info("flyTo destination:", centerLon, centerLat, "height:", height); - - cesiumViewer.camera.flyTo({ - destination, - orientation: { - heading: 0, - pitch: Cesium.Math.toRadians(-90), // Look straight down - roll: 0, - }, - duration, - complete: () => { - log.info( - "flyTo complete, camera height:", - cesiumViewer.camera.positionCartographic.height, - ); - resolve(); - }, - cancel: () => { - log.warn("flyTo cancelled"); - resolve(); - }, - }); - }); -} - -// Label element for displaying location info -let labelElement: HTMLDivElement | null = null; - -/** - * Set or clear the label displayed on the map - */ -function setLabel(text?: string): void { - if (!labelElement) { - labelElement = document.createElement("div"); - labelElement.style.cssText = ` - position: absolute; - top: 10px; - left: 10px; - background: rgba(0, 0, 0, 0.7); - color: white; - padding: 8px 12px; - border-radius: 4px; - font-family: sans-serif; - font-size: 14px; - z-index: 100; - pointer-events: none; - `; - document.body.appendChild(labelElement); - } - - if (text) { - labelElement.textContent = text; - labelElement.style.display = "block"; - } else { - labelElement.style.display = "none"; - } -} - /** * Wait for globe tiles to finish loading */ @@ -872,110 +801,57 @@ app.ontoolinput = async (params) => { } }; -// Register tools for the model to interact with this component -app.registerTool( - "navigate-to", - { - title: "Navigate To", - description: "Navigate the globe to a new bounding box location", - inputSchema: z.object({ - west: z.number().describe("Western longitude (-180 to 180)"), - south: z.number().describe("Southern latitude (-90 to 90)"), - east: z.number().describe("Eastern longitude (-180 to 180)"), - north: z.number().describe("Northern latitude (-90 to 90)"), - duration: z - .number() - .optional() - .describe("Animation duration in seconds (default: 2)"), - label: z.string().optional().describe("Optional label to display"), - }), - }, - async (args) => { - if (!viewer) { - return { - content: [ - { type: "text" as const, text: "Error: Viewer not initialized" }, - ], - isError: true, - }; - } +/* + Register tools for the model to interact w/ this component + Needs https://github.com/modelcontextprotocol/ext-apps/pull/72 +*/ +// app.registerTool( +// "navigate-to", +// { +// title: "Navigate To", +// description: "Navigate the globe to a new bounding box location", +// inputSchema: z.object({ +// west: z.number().describe("Western longitude (-180 to 180)"), +// south: z.number().describe("Southern latitude (-90 to 90)"), +// east: z.number().describe("Eastern longitude (-180 to 180)"), +// north: z.number().describe("Northern latitude (-90 to 90)"), +// duration: z +// .number() +// .optional() +// .describe("Animation duration in seconds (default: 2)"), +// label: z.string().optional().describe("Optional label to display"), +// }), +// }, +// async (args) => { +// if (!viewer) { +// return { +// content: [ +// { type: "text" as const, text: "Error: Viewer not initialized" }, +// ], +// isError: true, +// }; +// } - const bbox: BoundingBox = { - west: args.west, - south: args.south, - east: args.east, - north: args.north, - }; +// const bbox: BoundingBox = { +// west: args.west, +// south: args.south, +// east: args.east, +// north: args.north, +// }; - await flyToBoundingBox(viewer, bbox, args.duration ?? 2); - setLabel(args.label); +// await flyToBoundingBox(viewer, bbox, args.duration ?? 2); +// setLabel(args.label); - return { - content: [ - { - type: "text" as const, - text: `Navigated to: W:${bbox.west.toFixed(4)}, S:${bbox.south.toFixed(4)}, E:${bbox.east.toFixed(4)}, N:${bbox.north.toFixed(4)}${args.label ? ` (${args.label})` : ""}`, - }, - ], - }; - }, -); - -app.registerTool( - "get-current-view", - { - title: "Get Current View", - description: - "Get the current camera position and bounding box visible on the globe", - }, - async () => { - if (!viewer) { - return { - content: [ - { type: "text" as const, text: "Error: Viewer not initialized" }, - ], - isError: true, - }; - } - - const camera = viewer.camera; - const positionCartographic = camera.positionCartographic; - const latitude = Cesium.Math.toDegrees(positionCartographic.latitude); - const longitude = Cesium.Math.toDegrees(positionCartographic.longitude); - const height = positionCartographic.height; - - // Get the visible bounding box - const rectangle = viewer.camera.computeViewRectangle(); - let bbox = null; - if (rectangle) { - bbox = { - west: Cesium.Math.toDegrees(rectangle.west), - south: Cesium.Math.toDegrees(rectangle.south), - east: Cesium.Math.toDegrees(rectangle.east), - north: Cesium.Math.toDegrees(rectangle.north), - }; - } - - const viewData = { - camera: { - latitude, - longitude, - height, - }, - bbox, - }; - - return { - content: [ - { - type: "text" as const, - text: JSON.stringify(viewData, null, 2), - }, - ], - structuredContent: viewData, - }; - }, -); +// return { +// content: [ +// { +// type: "text" as const, +// text: `Navigated to: W:${bbox.west.toFixed(4)}, S:${bbox.south.toFixed(4)}, E:${bbox.east.toFixed(4)}, N:${bbox.north.toFixed(4)}${args.label ? ` (${args.label})` : ""}`, +// }, +// ], +// }; +// }, +// ); // Handle tool result - extract viewUUID and restore persisted view if available app.ontoolresult = async (result) => { diff --git a/examples/map-server/tsconfig.json b/examples/map-server/tsconfig.json index b028ff5..535267b 100644 --- a/examples/map-server/tsconfig.json +++ b/examples/map-server/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node", "vite/client"], "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "module": "ESNext", diff --git a/examples/map-server/tsconfig.server.json b/examples/map-server/tsconfig.server.json index 27eb28f..05ddd8e 100644 --- a/examples/map-server/tsconfig.server.json +++ b/examples/map-server/tsconfig.server.json @@ -1,6 +1,5 @@ { "compilerOptions": { - "types": ["node"], "target": "ES2022", "lib": ["ES2022"], "module": "NodeNext", diff --git a/examples/pdf-server/build-mcpb.mjs b/examples/pdf-server/build-mcpb.mjs index 2917334..c1c3469 100644 --- a/examples/pdf-server/build-mcpb.mjs +++ b/examples/pdf-server/build-mcpb.mjs @@ -43,21 +43,6 @@ writeFileSync( path.join(stage, "manifest.json"), JSON.stringify(manifest, null, 2), ); -// The bundle must ship the ext-apps build from this checkout, not whatever -// the registry has: pack the repo root and point the staged manifest at it. -const repoRoot = path.resolve(here, "..", ".."); -const packed = JSON.parse( - execSync( - "npm pack --json --ignore-scripts --pack-destination " + - JSON.stringify(stage), - { - cwd: repoRoot, - encoding: "utf8", - }, - ).replace(/^[^[]*/, ""), -); -pkg.dependencies["@modelcontextprotocol/ext-apps"] = - "file:./" + packed[0].filename; writeFileSync(path.join(stage, "package.json"), JSON.stringify(pkg, null, 2)); const run = (cmd) => execSync(cmd, { cwd: stage, stdio: "inherit" }); diff --git a/examples/pdf-server/main.ts b/examples/pdf-server/main.ts index bb7b57f..1ff848a 100644 --- a/examples/pdf-server/main.ts +++ b/examples/pdf-server/main.ts @@ -6,10 +6,10 @@ import fs from "node:fs"; import path from "node:path"; -import { createMcpExpressApp } from "@modelcontextprotocol/express"; -import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; -import type { McpServer } from "@modelcontextprotocol/server"; -import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import cors from "cors"; import type { Request, Response } from "express"; import { @@ -39,7 +39,7 @@ export async function startStreamableHTTPServer( app.all("/mcp", async (req: Request, res: Response) => { const server = createServer(); - const transport = new NodeStreamableHTTPServerTransport({ + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); diff --git a/examples/pdf-server/package.json b/examples/pdf-server/package.json index c8d9cf8..cdcda33 100644 --- a/examples/pdf-server/package.json +++ b/examples/pdf-server/package.json @@ -1,11 +1,11 @@ { "name": "@modelcontextprotocol/server-pdf", - "version": "2.0.0", + "version": "1.4.0", "type": "module", "description": "MCP server for loading and extracting text from PDF files with chunked pagination and interactive viewer", "repository": { "type": "git", - "url": "git+https://github.com/modelcontextprotocol/ext-apps.git", + "url": "https://github.com/modelcontextprotocol/ext-apps", "directory": "examples/pdf-server" }, "license": "MIT", @@ -25,16 +25,13 @@ "build:mcpb": "npm run build && node build-mcpb.mjs" }, "dependencies": { - "@cantoo/pdf-lib": "^2.6.5", - "@modelcontextprotocol/client": "2.0.0", - "@modelcontextprotocol/express": "2.0.0", - "@modelcontextprotocol/ext-apps": "^2.0.0", - "@modelcontextprotocol/node": "2.0.0", - "@modelcontextprotocol/server": "2.0.0", + "@modelcontextprotocol/ext-apps": "^1.0.0", + "@modelcontextprotocol/sdk": "^1.29.0", "cors": "^2.8.5", "express": "^5.1.0", + "pdf-lib": "^1.17.1", "pdfjs-dist": "^5.0.0", - "zod": "^4.2.0" + "zod": "^4.1.13" }, "devDependencies": { "@types/cors": "^2.8.19", diff --git a/examples/pdf-server/server.test.ts b/examples/pdf-server/server.test.ts index 0b2a5eb..a2f64ee 100644 --- a/examples/pdf-server/server.test.ts +++ b/examples/pdf-server/server.test.ts @@ -2,16 +2,11 @@ import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; -import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs"; -import { PDFDocument } from "@cantoo/pdf-lib"; -import { makeRandomJpeg } from "../../tests/helpers/range-counting-server"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { createPdfCache, createServer, - extractFormSchema, - PdfCacheRangeTransport, - MAX_CHUNK_BYTES, validateUrl, isAncestorDir, allowedLocalFiles, @@ -76,72 +71,6 @@ describe("PDF Cache with Timeouts", () => { }); }); - describe("byte-cap LRU eviction", () => { - const tenBytes = new Uint8Array(10); - - async function fill(cache: PdfCache, url: string): Promise { - const m = spyOn(globalThis, "fetch").mockResolvedValueOnce( - new Response(tenBytes, { status: 200 }), - ); - try { - await cache.readPdfRange(url, 0, 1024); - } finally { - m.mockRestore(); - } - } - - it("evicts least-recently-used entry when total exceeds cap", async () => { - const cache = createPdfCache(25); - try { - await fill(cache, "https://arxiv.org/pdf/a"); - await fill(cache, "https://arxiv.org/pdf/b"); - expect(cache.getCacheSize()).toBe(2); - - // Touch A so B becomes least-recently-used - await cache.readPdfRange("https://arxiv.org/pdf/a", 0, 1); - - // Inserting C (10B) pushes total to 30 > 25 → evict LRU (B) - await fill(cache, "https://arxiv.org/pdf/c"); - expect(cache.getCacheSize()).toBe(2); - - // A and C still served from cache; B re-fetches - const m = spyOn(globalThis, "fetch").mockResolvedValue( - new Response(tenBytes, { status: 200 }), - ); - try { - await cache.readPdfRange("https://arxiv.org/pdf/a", 0, 1); - await cache.readPdfRange("https://arxiv.org/pdf/c", 0, 1); - expect(m).toHaveBeenCalledTimes(0); - await cache.readPdfRange("https://arxiv.org/pdf/b", 0, 1); - expect(m).toHaveBeenCalledTimes(1); - } finally { - m.mockRestore(); - } - } finally { - cache.clearCache(); - } - }); - - it("evicts multiple entries if a single insert exceeds the cap", async () => { - const cache = createPdfCache(25); - try { - await fill(cache, "https://arxiv.org/pdf/a"); - await fill(cache, "https://arxiv.org/pdf/b"); - const big = spyOn(globalThis, "fetch").mockResolvedValueOnce( - new Response(new Uint8Array(20), { status: 200 }), - ); - try { - await cache.readPdfRange("https://arxiv.org/pdf/big", 0, 1024); - } finally { - big.mockRestore(); - } - expect(cache.getCacheSize()).toBe(1); - } finally { - cache.clearCache(); - } - }); - }); - describe("readPdfRange caching behavior", () => { const testUrl = "https://arxiv.org/pdf/test-pdf"; const testData = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF header @@ -294,266 +223,6 @@ describe("PDF Cache with Timeouts", () => { // through manual testing or E2E tests. }); -describe("PdfCacheRangeTransport", () => { - it("accumulates ranges larger than MAX_CHUNK_BYTES into one onDataRange call", async () => { - const big = MAX_CHUNK_BYTES * 2 + 100; - const reads: Array<[number, number]> = []; - const t = new PdfCacheRangeTransport("u", big, async (_u, off, n) => { - reads.push([off, n]); - return { - data: new Uint8Array(Math.min(n, MAX_CHUNK_BYTES)), - totalBytes: big, - }; - }); - const delivered: Array<[number, number]> = []; - t.addRangeListener((begin: number, chunk: Uint8Array) => - delivered.push([begin, chunk.length]), - ); - t.requestDataRange(0, big); - await new Promise((r) => setTimeout(r, 10)); - // pdf.js's reader is keyed by the original begin and removed after one - // delivery, so deliver() must call onDataRange exactly once with the - // accumulated buffer — multiple calls would throw inside pdfjs. - expect(delivered).toEqual([[0, big]]); - expect(reads).toEqual([ - [0, MAX_CHUNK_BYTES], - [MAX_CHUNK_BYTES, MAX_CHUNK_BYTES], - [MAX_CHUNK_BYTES * 2, 100], - ]); - }); - - it("rejects .failed when a range fetch errors instead of hanging", async () => { - const t = new PdfCacheRangeTransport("u", 1000, async () => { - throw new Error("network down"); - }); - t.requestDataRange(0, 100); - await expect( - Promise.race([ - t.failed, - new Promise((r) => setTimeout(() => r("timeout"), 200)), - ]), - ).rejects.toThrow("network down"); - }); - - it("rejects .failed on zero-length response (would otherwise spin)", async () => { - const t = new PdfCacheRangeTransport("u", 1000, async () => ({ - data: new Uint8Array(0), - totalBytes: 1000, - })); - t.requestDataRange(0, 100); - await expect(t.failed).rejects.toThrow(/empty range/); - }); - - it("getDocument resolves on a >1MB PDF when readPdfRange clamps to MAX_CHUNK_BYTES", async () => { - // pdfjs coalesces adjacent missing chunks into one requestDataRange that - // can exceed MAX_CHUNK_BYTES. deliver() must accumulate clamped reads and - // hand pdfjs a single onDataRange(begin, fullBuffer). This test fails if - // deliver() either truncates or calls onDataRange more than once per - // requestDataRange (pdf.mjs _onReceiveData matches by exact begin). - const d = await PDFDocument.create(); - const img = await d.embedJpg(makeRandomJpeg(1_100_000)); - const page = d.addPage([612, 792]); - page.drawImage(img, { x: 36, y: 36, width: 540, height: 720 }); - const bytes = await d.save(); - expect(bytes.length).toBeGreaterThan(2 * MAX_CHUNK_BYTES); - - const readClamped: PdfCache["readPdfRange"] = async (_u, off, n) => { - const len = Math.min(n, MAX_CHUNK_BYTES, bytes.length - off); - return { data: bytes.slice(off, off + len), totalBytes: bytes.length }; - }; - // Record the spans pdfjs actually requests so the test fails fast if it - // never asks for >MAX_CHUNK_BYTES (i.e. can't go vacuously green). - const spans: number[] = []; - class RecordingTransport extends PdfCacheRangeTransport { - override requestDataRange(begin: number, end: number): void { - spans.push(end - begin); - super.requestDataRange(begin, end); - } - } - const transport = new RecordingTransport( - "mem://big", - bytes.length, - readClamped, - ); - - const orHang = (p: Promise, what: string): Promise => - Promise.race([ - p, - transport.failed, - new Promise((_, rej) => - setTimeout(() => rej(new Error(`${what} hung`)), 5000), - ), - ]); - - const doc = await orHang( - getDocument({ - range: transport, - length: bytes.length, - disableAutoFetch: true, - disableStream: true, - rangeChunkSize: 64 * 1024, - }).promise, - "getDocument", - ); - const p1 = await orHang(doc.getPage(1), "getPage"); - // getPage() alone doesn't decode the image XObject; getOperatorList() does, - // which is what triggers the >512KB coalesced range request. - await orHang(p1.getOperatorList(), "getOperatorList"); - expect(Math.max(...spans)).toBeGreaterThan(MAX_CHUNK_BYTES); - doc.destroy(); - }); -}); - -describe("display_pdf transport-error handling", () => { - it("returns (does not hang) when range fetches fail mid-load", async () => { - // First fetch = the 1-byte size probe → 206 with Content-Range so - // display_pdf gets totalBytes. Every subsequent fetch (made by - // PdfCacheRangeTransport via readPdfRange) rejects, which must surface - // through transport.failed → orFail() → outer catch, not hang. - let calls = 0; - const mockFetch = spyOn(globalThis, "fetch").mockImplementation( - async () => { - if (calls++ === 0) { - return new Response(new Uint8Array(1), { - status: 206, - headers: { "Content-Range": "bytes 0-0/50000" }, - }); - } - throw new Error("network down"); - }, - ); - - const server = createServer(); - const client = new Client({ name: "t", version: "1" }); - const [ct, st] = InMemoryTransport.createLinkedPair(); - await Promise.all([server.connect(st), client.connect(ct)]); - - try { - const result = await Promise.race([ - client.callTool({ - name: "display_pdf", - arguments: { url: "https://arxiv.org/pdf/err-test" }, - }), - new Promise((_, rej) => - setTimeout( - () => rej(new Error("display_pdf hung on transport error")), - 3000, - ), - ), - ]); - expect(result.isError).toBeFalsy(); - const sc = result.structuredContent as { formFields?: unknown }; - expect(sc.formFields).toBeUndefined(); - expect(calls).toBeGreaterThan(1); - } finally { - mockFetch.mockRestore(); - await client.close(); - await server.close(); - } - }); -}); - -describe("extractFormSchema field-tree handling", () => { - async function schemaFor(bytes: Uint8Array) { - const doc = await getDocument({ data: bytes }).promise; - try { - const fo = (await doc.getFieldObjects()) as Parameters< - typeof extractFormSchema - >[1]; - return await extractFormSchema(doc, fo); - } finally { - doc.destroy(); - } - } - - it("handles pdf-lib separated field/widget structure", async () => { - const d = await PDFDocument.create(); - const form = d.getForm(); - d.addPage([612, 792]); - form - .createTextField("alpha") - .addToPage(d.getPage(0), { x: 50, y: 700, width: 200, height: 20 }); - form - .createCheckBox("agree") - .addToPage(d.getPage(0), { x: 50, y: 660, width: 20, height: 20 }); - form - .createDropdown("choice") - .addToPage(d.getPage(0), { x: 50, y: 620, width: 100, height: 20 }); - - const schema = await schemaFor(await d.save()); - expect(schema).not.toBeNull(); - expect(schema!.properties.alpha).toEqual({ - type: "string", - title: "alpha", - }); - expect(schema!.properties.agree).toEqual({ - type: "boolean", - title: "agree", - }); - expect(schema!.properties.choice.type).toBe("string"); - }); - - it("handles fields with multiple widgets across pages", async () => { - const d = await PDFDocument.create(); - const form = d.getForm(); - d.addPage([612, 792]); - d.addPage([612, 792]); - const tf = form.createTextField("shared"); - tf.addToPage(d.getPage(0), { x: 50, y: 700, width: 200, height: 20 }); - tf.addToPage(d.getPage(1), { x: 50, y: 700, width: 200, height: 20 }); - - const schema = await schemaFor(await d.save()); - expect(schema?.properties.shared).toEqual({ - type: "string", - title: "shared", - }); - }); - - it("skips container nodes and finds leaf fields (W-9 style)", async () => { - const bytes = fs.readFileSync( - path.join(__dirname, "../../tests/helpers/assets/fw9.pdf"), - ); - const doc = await getDocument({ data: new Uint8Array(bytes) }).promise; - try { - const fo = (await doc.getFieldObjects()) as Parameters< - typeof extractFormSchema - >[1]; - // Container nodes (no leaf type) should not crash extraction - expect(fo!["topmostSubform[0]"]).toBeDefined(); - // Schema is null for W-9 (mechanical names), but extraction must not throw - const schema = await extractFormSchema(doc, fo); - expect(schema).toBeNull(); - } finally { - doc.destroy(); - } - }); - - it("returns null when no AcroForm present", async () => { - const d = await PDFDocument.create(); - d.addPage([612, 792]); - const schema = await schemaFor(await d.save()); - expect(schema).toBeNull(); - }); -}); - -describe("validateUrl loopback HTTP allow (PDF_SERVER_ALLOW_LOOPBACK_HTTP)", () => { - it("rejects http://127.0.0.1 by default", () => { - expect(validateUrl("http://127.0.0.1:9999/x.pdf").valid).toBe(false); - }); - - it("accepts http://127.0.0.1 only when the env gate is set, and never non-loopback http", () => { - const prev = process.env.PDF_SERVER_ALLOW_LOOPBACK_HTTP; - process.env.PDF_SERVER_ALLOW_LOOPBACK_HTTP = "1"; - try { - expect(validateUrl("http://127.0.0.1:9999/x.pdf").valid).toBe(true); - expect(validateUrl("http://169.254.169.254/").valid).toBe(false); - } finally { - if (prev === undefined) delete process.env.PDF_SERVER_ALLOW_LOOPBACK_HTTP; - else process.env.PDF_SERVER_ALLOW_LOOPBACK_HTTP = prev; - } - }); -}); - describe("validateUrl with MCP roots (allowedLocalDirs)", () => { const savedFiles = new Set(allowedLocalFiles); const savedDirs = new Set(allowedLocalDirs); diff --git a/examples/pdf-server/server.ts b/examples/pdf-server/server.ts index e67cd47..ba16431 100644 --- a/examples/pdf-server/server.ts +++ b/examples/pdf-server/server.ts @@ -13,30 +13,27 @@ import { randomUUID } from "crypto"; import fs from "node:fs"; import path from "node:path"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE, } from "@modelcontextprotocol/ext-apps/server"; import { - McpServer, + RootsListChangedNotificationSchema, type CallToolResult, - type ElicitResult, - type PrimitiveSchemaDefinition, type ReadResourceResult, - type Server, -} from "@modelcontextprotocol/server"; +} from "@modelcontextprotocol/sdk/types.js"; // Stub DOMMatrix/ImageData/Path2D before pdfjs-dist loads — its legacy // build instantiates DOMMatrix at module scope and the @napi-rs/canvas // polyfill is unreliable under npx. See ./pdfjs-polyfill.ts for details. import "./pdfjs-polyfill.js"; import { getDocument, - PDFDataRangeTransport, VerbosityLevel, version as PDFJS_VERSION, } from "pdfjs-dist/legacy/build/pdf.mjs"; -import type { PDFDocumentProxy } from "pdfjs-dist/types/src/display/api.js"; /** * PDF Standard-14 fonts from CDN. Used by both server and viewer so we @@ -63,6 +60,10 @@ class FetchStandardFontDataFactory { return new Uint8Array(await res.arrayBuffer()); } } +import type { + PrimitiveSchemaDefinition, + ElicitResult, +} from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; // ============================================================================= @@ -82,9 +83,6 @@ export const CACHE_MAX_LIFETIME_MS = 60_000; // 60 seconds /** Max size for cached PDFs (defensive limit to prevent memory exhaustion) */ export const CACHE_MAX_PDF_SIZE_BYTES = 50 * 1024 * 1024; // 50MB -/** Max total bytes across all cache entries; oldest evicted first when exceeded. */ -export const CACHE_MAX_TOTAL_BYTES = 256 * 1024 * 1024; // 256MB - /** Allowed local file paths (CLI args + file roots — read access). */ export const allowedLocalFiles = new Set(); @@ -307,33 +305,6 @@ function waitForSaveData( }); } -const pendingStateRequests = new Map void>(); - -/** - * Wait for the viewer to report its current state (page, zoom, selection, …) - * as a JSON string. Same timeout/abort semantics as waitForSaveData. - */ -function waitForViewerState( - requestId: string, - signal?: AbortSignal, -): Promise { - return new Promise((resolve, reject) => { - const settle = (v: string | Error) => { - clearTimeout(timer); - signal?.removeEventListener("abort", onAbort); - pendingStateRequests.delete(requestId); - v instanceof Error ? reject(v) : resolve(v); - }; - const onAbort = () => settle(new Error("interact request cancelled")); - const timer = setTimeout( - () => settle(new Error("Timeout waiting for viewer state")), - GET_PAGES_TIMEOUT_MS, - ); - signal?.addEventListener("abort", onAbort); - pendingStateRequests.set(requestId, settle); - }); -} - interface QueueEntry { commands: PdfCommand[]; /** Timestamp of the most recent enqueue or dequeue */ @@ -366,6 +337,9 @@ export const viewSourcePaths = new Map(); /** Valid form field names per viewer UUID (populated during display_pdf) */ const viewFieldNames = new Map>(); +/** Detailed form field info per viewer UUID (populated during display_pdf) */ +const viewFieldInfo = new Map(); + /** * Active fs.watch per view. Only created for local files when interact is * enabled (stdio). Watcher is re-established on `rename` events to survive @@ -382,7 +356,7 @@ const viewFileWatches = new Map(); /** * Per-view heartbeat. THIS is what the sweep iterates — not commandQueues. * - * Why not commandQueues: display_pdf populates viewFieldNames/ + * Why not commandQueues: display_pdf populates viewFieldNames/viewFieldInfo/ * viewFileWatches but never touches commandQueues (only enqueueCommand does, * and it's triply gated). And dequeueCommands deletes the entry on every poll, * so even when it exists the sweep's TTL window is ~200ms wide. Net effect: @@ -404,6 +378,7 @@ function pruneStaleQueues(): void { viewLastActivity.delete(uuid); commandQueues.delete(uuid); viewFieldNames.delete(uuid); + viewFieldInfo.delete(uuid); viewsPolled.delete(uuid); viewSourcePaths.delete(uuid); stopFileWatch(uuid); @@ -638,19 +613,10 @@ export function validateUrl(url: string): { // Remote URL - require HTTPS try { const parsed = new URL(url); - if (parsed.protocol === "https:") return { valid: true }; - // Loopback HTTP is opt-in (test fixtures, local dev). Off by default so a - // remotely-deployed server can't be made to probe its own internal ports. - if ( - process.env.PDF_SERVER_ALLOW_LOOPBACK_HTTP && - parsed.protocol === "http:" && - (parsed.hostname === "127.0.0.1" || - parsed.hostname === "localhost" || - parsed.hostname === "[::1]") - ) { - return { valid: true }; + if (parsed.protocol !== "https:") { + return { valid: false, error: `Only HTTPS URLs are allowed: ${url}` }; } - return { valid: false, error: `Only HTTPS URLs are allowed: ${url}` }; + return { valid: true }; } catch { return { valid: false, error: `Invalid URL: ${url}` }; } @@ -702,11 +668,8 @@ export interface PdfCache { * - CACHE_INACTIVITY_TIMEOUT_MS of no access (resets on each access) * - CACHE_MAX_LIFETIME_MS from creation (absolute timeout) */ -export function createPdfCache( - maxTotalBytes: number = CACHE_MAX_TOTAL_BYTES, -): PdfCache { +export function createPdfCache(): PdfCache { const cache = new Map(); - let totalBytes = 0; /** Delete a cache entry and clear its timers */ function deleteCacheEntry(url: string): void { @@ -714,7 +677,6 @@ export function createPdfCache( if (entry) { clearTimeout(entry.inactivityTimer); clearTimeout(entry.maxLifetimeTimer); - totalBytes -= entry.data.length; cache.delete(url); } } @@ -730,10 +692,6 @@ export function createPdfCache( deleteCacheEntry(url); }, CACHE_INACTIVITY_TIMEOUT_MS); - // Move to end of insertion order so size-cap eviction is LRU. - cache.delete(url); - cache.set(url, entry); - return entry.data; } @@ -742,12 +700,6 @@ export function createPdfCache( // Clear any existing entry first deleteCacheEntry(url); - // Evict least-recently-used entries until under the byte cap. - for (const oldest of cache.keys()) { - if (totalBytes + data.length <= maxTotalBytes) break; - deleteCacheEntry(oldest); - } - const entry: CacheEntry = { data, createdAt: Date.now(), @@ -760,7 +712,6 @@ export function createPdfCache( }; cache.set(url, entry); - totalBytes += data.length; } /** Slice a cached or freshly-fetched full body to the requested range. */ @@ -885,61 +836,6 @@ export function createPdfCache( }; } -/** - * pdf.js range transport backed by {@link PdfCache.readPdfRange}. Lets - * getDocument() fetch only the byte ranges it needs (xref, /AcroForm dict) - * instead of the whole file. With disableAutoFetch, a PDF without form - * fields is opened with ~5% of bytes fetched. - * - * pdf.js has no upstream error channel on PDFDataRangeTransport (its - * `abort()` is a no-op stub it calls *on* us, not the other way). Callers - * must `Promise.race` their pdf.js awaits against {@link failed}, which - * rejects on the first fetch error. - */ -export class PdfCacheRangeTransport extends PDFDataRangeTransport { - /** Rejects on the first range-fetch error; never resolves. */ - readonly failed: Promise; - private fail!: (e: unknown) => void; - - constructor( - private url: string, - length: number, - private readPdfRange: PdfCache["readPdfRange"], - ) { - super(length, null); - this.failed = new Promise((_, reject) => { - this.fail = reject; - }); - // Don't crash the process if no one is racing yet. - this.failed.catch(() => {}); - } - - override requestDataRange(begin: number, end: number): void { - void this.deliver(begin, end).catch((e) => this.fail(e)); - } - - /** - * pdf.js coalesces adjacent missing chunks into one unbounded request, but - * readPdfRange clamps each call to MAX_CHUNK_BYTES. Its reader is keyed by - * the original `begin` and removed after one delivery, so we must accumulate - * slices and call onDataRange exactly once with the full buffer. - */ - private async deliver(begin: number, end: number): Promise { - const buf = new Uint8Array(end - begin); - let off = 0; - while (off < buf.length) { - const want = Math.min(buf.length - off, MAX_CHUNK_BYTES); - const { data } = await this.readPdfRange(this.url, begin + off, want); - if (data.length === 0) { - throw new Error(`empty range at ${begin + off} for ${this.url}`); - } - buf.set(data.subarray(0, Math.min(data.length, buf.length - off)), off); - off += data.length; - } - this.onDataRange(begin, buf); - } -} - // ============================================================================= // MCP Roots // ============================================================================= @@ -1015,142 +911,135 @@ interface FormFieldInfo { options?: string[]; } -/** - * Open `url` via {@link PdfCacheRangeTransport} and return form metadata. - * Uses `disableAutoFetch` so PDFs without an AcroForm are probed with only - * the trailer/xref/catalog (~5-25% of bytes); PDFs with forms still walk - * every page via {@link extractFormFieldInfo} but those are typically small. - * All errors (including range-fetch failures surfaced via - * {@link PdfCacheRangeTransport.failed}) resolve to empty results. - */ -async function probeFormFields( - url: string, - totalBytes: number, - readPdfRange: PdfCache["readPdfRange"], -): Promise<{ - formSchema: Awaited>; - fieldInfo: FormFieldInfo[]; -}> { - // Assigned sequentially below so a throw in extractFormFieldInfo (no per-page - // guard, unlike extractFormSchema) doesn't discard an already-computed schema. - let formSchema: Awaited> = null; - let fieldInfo: FormFieldInfo[] = []; - try { - const transport = new PdfCacheRangeTransport(url, totalBytes, readPdfRange); - const orFail = (p: Promise): Promise => - Promise.race([p, transport.failed]); - const pdfDoc = await orFail( - getDocument({ - range: transport, - length: totalBytes, - disableAutoFetch: true, - disableStream: true, - rangeChunkSize: 64 * 1024, - standardFontDataUrl: STANDARD_FONT_DATA_URL, - StandardFontDataFactory: FetchStandardFontDataFactory, - verbosity: VerbosityLevel.ERRORS, - }).promise, - ); - try { - const fieldObjects = (await orFail(pdfDoc.getFieldObjects())) as Record< - string, - PdfJsFieldObject[] - > | null; - if (fieldObjects && Object.keys(fieldObjects).length > 0) { - formSchema = await orFail(extractFormSchema(pdfDoc, fieldObjects)); - fieldInfo = await orFail(extractFormFieldInfo(pdfDoc)); - } - } finally { - pdfDoc.destroy(); - } - } catch { - // Non-fatal — return whatever was assigned before the throw. - } - return { formSchema, fieldInfo }; -} - /** * Extract detailed form field info (name, type, page, bounding box, label) * from a PDF. Bounding boxes are converted to model coordinates (top-left origin). */ async function extractFormFieldInfo( - pdfDoc: PDFDocumentProxy, + url: string, + readRange: ( + url: string, + offset: number, + byteCount: number, + ) => Promise<{ data: Uint8Array; totalBytes: number }>, ): Promise { + const { totalBytes } = await readRange(url, 0, 1); + const { data } = await readRange(url, 0, totalBytes); + + const loadingTask = getDocument({ + data, + standardFontDataUrl: STANDARD_FONT_DATA_URL, + StandardFontDataFactory: FetchStandardFontDataFactory, + // We only introspect form fields (never render) — silence residual + // warnings like "Unimplemented border style: inset". + verbosity: VerbosityLevel.ERRORS, + }); + const pdfDoc = await loadingTask.promise; + const fields: FormFieldInfo[] = []; - for (let i = 1; i <= pdfDoc.numPages; i++) { - const page = await pdfDoc.getPage(i); - const pageHeight = page.getViewport({ scale: 1.0 }).height; - const annotations = await page.getAnnotations(); - for (const ann of annotations) { - // Only include form widgets (annotationType 20) - if (ann.annotationType !== 20) continue; - if (!ann.rect) continue; + try { + for (let i = 1; i <= pdfDoc.numPages; i++) { + const page = await pdfDoc.getPage(i); + const pageHeight = page.getViewport({ scale: 1.0 }).height; + const annotations = await page.getAnnotations(); + for (const ann of annotations) { + // Only include form widgets (annotationType 20) + if (ann.annotationType !== 20) continue; + if (!ann.rect) continue; - const fieldName = ann.fieldName || ""; - const fieldType = ann.fieldType || "unknown"; + const fieldName = ann.fieldName || ""; + const fieldType = ann.fieldType || "unknown"; - // PDF rect is [x1, y1, x2, y2] in bottom-left origin - const x1 = Math.min(ann.rect[0], ann.rect[2]); - const y1 = Math.min(ann.rect[1], ann.rect[3]); - const x2 = Math.max(ann.rect[0], ann.rect[2]); - const y2 = Math.max(ann.rect[1], ann.rect[3]); - const width = x2 - x1; - const height = y2 - y1; + // PDF rect is [x1, y1, x2, y2] in bottom-left origin + const x1 = Math.min(ann.rect[0], ann.rect[2]); + const y1 = Math.min(ann.rect[1], ann.rect[3]); + const x2 = Math.max(ann.rect[0], ann.rect[2]); + const y2 = Math.max(ann.rect[1], ann.rect[3]); + const width = x2 - x1; + const height = y2 - y1; - // Convert to model coords (top-left origin): modelY = pageHeight - pdfY - height - const modelY = pageHeight - y2; + // Convert to model coords (top-left origin): modelY = pageHeight - pdfY - height + const modelY = pageHeight - y2; - // Choice widgets (combo/listbox) carry `options` as - // [{exportValue, displayValue}]. Expose export values — that's - // what fill_form needs. - let options: string[] | undefined; - if (Array.isArray(ann.options) && ann.options.length > 0) { - options = ann.options - .map((o: { exportValue?: string }) => o?.exportValue) - .filter((v: unknown): v is string => typeof v === "string"); + // Choice widgets (combo/listbox) carry `options` as + // [{exportValue, displayValue}]. Expose export values — that's + // what fill_form needs. + let options: string[] | undefined; + if (Array.isArray(ann.options) && ann.options.length > 0) { + options = ann.options + .map((o: { exportValue?: string }) => o?.exportValue) + .filter((v: unknown): v is string => typeof v === "string"); + } + + fields.push({ + name: fieldName, + type: fieldType, + page: i, + x: Math.round(x1), + y: Math.round(modelY), + width: Math.round(width), + height: Math.round(height), + ...(ann.alternativeText ? { label: ann.alternativeText } : undefined), + // Radio: buttonValue is the per-widget export value — the only + // thing distinguishing three `size [Btn]` lines from each other. + ...(ann.radioButton && ann.buttonValue != null + ? { exportValue: String(ann.buttonValue) } + : undefined), + ...(options?.length ? { options } : undefined), + }); } - - fields.push({ - name: fieldName, - type: fieldType, - page: i, - x: Math.round(x1), - y: Math.round(modelY), - width: Math.round(width), - height: Math.round(height), - ...(ann.alternativeText ? { label: ann.alternativeText } : undefined), - // Radio: buttonValue is the per-widget export value — the only - // thing distinguishing three `size [Btn]` lines from each other. - ...(ann.radioButton && ann.buttonValue != null - ? { exportValue: String(ann.buttonValue) } - : undefined), - ...(options?.length ? { options } : undefined), - }); } + } finally { + pdfDoc.destroy(); } return fields; } -export async function extractFormSchema( - pdfDoc: PDFDocumentProxy, - fieldObjects: Record | null, +async function extractFormSchema( + url: string, + readRange: ( + url: string, + offset: number, + byteCount: number, + ) => Promise<{ data: Uint8Array; totalBytes: number }>, ): Promise<{ type: "object"; properties: Record; required?: string[]; } | null> { + // Read full PDF bytes + const { totalBytes } = await readRange(url, 0, 1); + const { data } = await readRange(url, 0, totalBytes); + + const loadingTask = getDocument({ + data, + standardFontDataUrl: STANDARD_FONT_DATA_URL, + StandardFontDataFactory: FetchStandardFontDataFactory, + // We only introspect form fields (never render) — silence residual + // warnings like "Unimplemented border style: inset". + verbosity: VerbosityLevel.ERRORS, + }); + const pdfDoc = await loadingTask.promise; + + let fieldObjects: Record | null; + try { + fieldObjects = (await pdfDoc.getFieldObjects()) as Record< + string, + PdfJsFieldObject[] + > | null; + } catch { + pdfDoc.destroy(); + return null; + } if (!fieldObjects || Object.keys(fieldObjects).length === 0) { + pdfDoc.destroy(); return null; } const properties: Record = {}; for (const [name, fields] of Object.entries(fieldObjects)) { - // pdfjs returns the full field-tree array: for separated structures - // (pdf-lib) the typed widget is at [1+] behind a container at [0]; for - // merged/leaf entries (W-9, most authoring tools) it's at [0]. Pick the - // first entry that actually has a field type. - const field = fields.find((f) => f.type) ?? fields[0]; + const field = fields[0]; // first widget determines the type if (!field.editable) continue; switch (field.type) { @@ -1215,6 +1104,7 @@ export async function extractFormSchema( return /[[\]().]/.test(name) || /^[A-Z0-9_]+$/.test(name); }); + pdfDoc.destroy(); if (Object.keys(properties).length === 0) return null; if (hasMechanicalNames) return null; @@ -1261,12 +1151,6 @@ export interface CreateServerOptions { debug?: boolean; } -// Module-level singletons so they survive across createServer() calls — in -// stateless HTTP deployments a fresh server is created per request, and -// per-instance caches are discarded immediately. -const sharedPdfCache = createPdfCache(); -let cachedAppHtml: string | undefined; - export function createServer(options: CreateServerOptions = {}): McpServer { const { enableInteract = false, useClientRoots = false } = options; const debug = options.debug ?? false; @@ -1279,22 +1163,21 @@ export function createServer(options: CreateServerOptions = {}): McpServer { refreshRoots(server.server); }; server.server.setNotificationHandler( - "notifications/roots/list_changed", + RootsListChangedNotificationSchema, async () => { await refreshRoots(server.server); }, ); } - const { readPdfRange } = sharedPdfCache; + // Create session-local cache (isolated per server instance) + const { readPdfRange } = createPdfCache(); // Tool: list_pdfs - List available PDFs - server.registerTool( + server.tool( "list_pdfs", - { - description: "List available PDFs that can be displayed", - inputSchema: z.object({}), - }, + "List available PDFs that can be displayed", + {}, async (): Promise => { const seen = new Set(); const localFiles: string[] = []; @@ -1376,7 +1259,7 @@ export function createServer(options: CreateServerOptions = {}): McpServer { title: "Read PDF Bytes", description: "Read a range of bytes from a PDF (max 512KB per request). The model should NOT call this tool directly.", - inputSchema: z.object({ + inputSchema: { url: z.string().describe("PDF URL or local file path"), offset: z.number().min(0).default(0).describe("Byte offset"), byteCount: z @@ -1385,7 +1268,7 @@ export function createServer(options: CreateServerOptions = {}): McpServer { .max(MAX_CHUNK_BYTES) .default(MAX_CHUNK_BYTES) .describe("Bytes to read"), - }), + }, outputSchema: z.object({ url: z.string(), bytes: z.string().describe("Base64 encoded bytes"), @@ -1456,7 +1339,7 @@ export function createServer(options: CreateServerOptions = {}): McpServer { description: disableInteract ? `Show and render a PDF in a read-only viewer. -Use this tool when the user wants to view or read a PDF. The renderer displays the document for viewing. The widget exposes app-registered tools for page navigation, text extraction, searching, and zoom control. +Use this tool when the user wants to view or read a PDF. The renderer displays the document for viewing. Accepts local files (use list_pdfs), client MCP root directories, or any HTTPS URL.` : `Open a PDF in an interactive viewer. Call this ONCE per PDF. @@ -1467,12 +1350,11 @@ Returns a viewUUID in structuredContent. Pass it to \`interact\`: - add_annotations, update_annotations, remove_annotations, highlight_text - fill_form (fill PDF form fields) - navigate, search, find, search_navigate, zoom -- get_text, get_screenshot, get_viewer_state (extract content / read selection & current page) -- save_as (write annotated PDF to disk) +- get_text, get_screenshot (extract content) Accepts local files (use list_pdfs), client MCP root directories, or any HTTPS URL. Set \`elicit_form_inputs\` to true to prompt the user to fill form fields before display.`, - inputSchema: z.object({ + inputSchema: { url: z .string() .default(DEFAULT_PDF) @@ -1488,7 +1370,7 @@ Set \`elicit_form_inputs\` to true to prompt the user to fill form fields before "If true and the PDF has form fields, prompt the user to fill them before displaying", ), }), - }), + }, outputSchema: z.object({ viewUUID: z .string() @@ -1546,7 +1428,7 @@ Set \`elicit_form_inputs\` to true to prompt the user to fill form fields before const { totalBytes } = await readPdfRange(normalized, 0, 1); const uuid = randomUUID(); // Start the heartbeat now so the sweep can clean up viewFieldNames/ - // viewFileWatches even if no interact calls ever happen. + // viewFieldInfo/viewFileWatches even if no interact calls ever happen. if (!disableInteract) touchView(uuid); // Check writability (governs save button; see isWritablePath doc). @@ -1574,19 +1456,33 @@ Set \`elicit_form_inputs\` to true to prompt the user to fill form fields before } } - const { formSchema, fieldInfo } = await probeFormFields( - normalized, - totalBytes, - readPdfRange, - ); + // Extract form field schema (used for elicitation and field name validation) + let formSchema: Awaited> = null; + try { + formSchema = await extractFormSchema(normalized, readPdfRange); + } catch { + // Non-fatal — PDF may not have form fields + } if (formSchema) { viewFieldNames.set(uuid, new Set(Object.keys(formSchema.properties))); } - if (fieldInfo.length > 0 && !viewFieldNames.has(uuid)) { - viewFieldNames.set( - uuid, - new Set(fieldInfo.map((f) => f.name).filter(Boolean)), - ); + + // Extract detailed form field info (page, bounding box, label) + let fieldInfo: FormFieldInfo[] = []; + try { + fieldInfo = await extractFormFieldInfo(normalized, readPdfRange); + if (fieldInfo.length > 0) { + viewFieldInfo.set(uuid, fieldInfo); + // Also populate viewFieldNames from field info if not already set + if (!viewFieldNames.has(uuid)) { + viewFieldNames.set( + uuid, + new Set(fieldInfo.map((f) => f.name).filter(Boolean)), + ); + } + } + } catch { + // Non-fatal } // Elicit form field values if requested and client supports it @@ -1754,7 +1650,6 @@ URL: ${normalized}`, "fill_form", "get_text", "get_screenshot", - "get_viewer_state", "save_as", ]) .describe("Action to perform"), @@ -2343,26 +2238,6 @@ URL: ${normalized}`, ); } } - case "get_viewer_state": { - const requestId = randomUUID(); - enqueueCommand(uuid, { type: "get_viewer_state", requestId }); - let state: string; - try { - await ensureViewerIsPolling(uuid); - state = await waitForViewerState(requestId, signal); - } catch (err) { - return { - content: [ - { - type: "text", - text: `Error: ${err instanceof Error ? err.message : String(err)}`, - }, - ], - isError: true, - }; - } - return { content: [{ type: "text", text: state }] }; - } default: return { content: [{ type: "text", text: `Unknown action: ${action}` }], @@ -2420,12 +2295,11 @@ Example — add a signature image and a stamp, then screenshot to verify: **TEXT/SCREENSHOTS**: • get_text: extract text from pages. Optional \`page\` for single page, or \`intervals\` for ranges [{start?,end?}]. Max 20 pages. • get_screenshot: capture a single page as PNG image. Requires \`page\`. -• get_viewer_state: snapshot of the live viewer — JSON {currentPage, pageCount, zoom, displayMode, selectedAnnotationIds, selection:{text,contextBefore,contextAfter,boundingRect}|null}. Use this to read what the user has selected or which page they're on. **FORMS** — fill_form: fill fields with \`fields\` array of {name, value}. **SAVE** — save_as: write the annotated PDF (annotations + form values) to a file. Pass \`path\` (absolute path or file://) for a new location, or omit \`path\` to overwrite the original. Set \`overwrite: true\` to replace an existing file (always required when omitting \`path\`).`, - inputSchema: z.object({ + inputSchema: { viewUUID: z .string() .describe( @@ -2446,7 +2320,6 @@ Example — add a signature image and a stamp, then screenshot to verify: "fill_form", "get_text", "get_screenshot", - "get_viewer_state", "save_as", ]) .optional() @@ -2522,7 +2395,7 @@ Example — add a signature image and a stamp, then screenshot to verify: .describe( "Array of commands to execute sequentially. More efficient than separate calls. Tip: end with get_pages+getScreenshots to verify changes.", ), - }), + }, }, async ( { @@ -2599,7 +2472,7 @@ Example — add a signature image and a stamp, then screenshot to verify: const result = await processInteractCommand( uuid, commandList[i], - extra.mcpReq.signal, + extra.signal, ); if (result.isError) { const errText = result.content @@ -2656,7 +2529,7 @@ Example — add a signature image and a stamp, then screenshot to verify: title: "Submit Page Data", description: "Submit rendered page data for a get_pages request (used by viewer). The model should NOT call this tool directly.", - inputSchema: z.object({ + inputSchema: { requestId: z .string() .describe("The request ID from the get_pages command"), @@ -2669,7 +2542,7 @@ Example — add a signature image and a stamp, then screenshot to verify: }), ) .describe("Page data entries"), - }), + }, _meta: { ui: { visibility: ["app"] } }, }, async ({ requestId, pages }): Promise => { @@ -2699,7 +2572,7 @@ Example — add a signature image and a stamp, then screenshot to verify: title: "Submit Save Data", description: "Submit annotated PDF bytes for a save_as request (used by viewer). The model should NOT call this tool directly.", - inputSchema: z.object({ + inputSchema: { requestId: z .string() .describe("The request ID from the save_as command"), @@ -2708,7 +2581,7 @@ Example — add a signature image and a stamp, then screenshot to verify: .string() .optional() .describe("Error message if the viewer failed to build bytes"), - }), + }, _meta: { ui: { visibility: ["app"] } }, }, async ({ requestId, data, error }): Promise => { @@ -2730,48 +2603,6 @@ Example — add a signature image and a stamp, then screenshot to verify: }, ); - // Tool: submit_viewer_state (app-only) - Viewer reports its live state - registerAppTool( - server, - "submit_viewer_state", - { - title: "Submit Viewer State", - description: - "Submit a viewer-state snapshot for a get_viewer_state request (used by viewer). The model should NOT call this tool directly.", - inputSchema: z.object({ - requestId: z - .string() - .describe("The request ID from the get_viewer_state command"), - state: z - .string() - .optional() - .describe("JSON-encoded viewer state snapshot"), - error: z - .string() - .optional() - .describe("Error message if the viewer failed to read state"), - }), - _meta: { ui: { visibility: ["app"] } }, - }, - async ({ requestId, state, error }): Promise => { - const settle = pendingStateRequests.get(requestId); - if (!settle) { - return { - content: [ - { type: "text", text: `No pending request for ${requestId}` }, - ], - isError: true, - }; - } - if (error || !state) { - settle(new Error(error || "Viewer returned no state")); - } else { - settle(state); - } - return { content: [{ type: "text", text: "Submitted" }] }; - }, - ); - // Tool: poll_pdf_commands (app-only) - Poll for pending commands registerAppTool( server, @@ -2780,9 +2611,9 @@ Example — add a signature image and a stamp, then screenshot to verify: title: "Poll PDF Commands", description: "Poll for pending commands for a PDF viewer. The model should NOT call this tool directly.", - inputSchema: z.object({ + inputSchema: { viewUUID: z.string().describe("The viewUUID of the PDF viewer"), - }), + }, _meta: { ui: { visibility: ["app"] } }, }, async ({ viewUUID: uuid }): Promise => { @@ -2827,10 +2658,10 @@ Example — add a signature image and a stamp, then screenshot to verify: title: "Save PDF", description: "Save annotated PDF bytes back to a local file. The model should NOT call this tool directly — use interact with action: save_as instead.", - inputSchema: z.object({ + inputSchema: { url: z.string().describe("Original PDF URL or local file path"), data: z.string().describe("Base64-encoded PDF bytes"), - }), + }, outputSchema: z.object({ filePath: z.string(), mtimeMs: z.number(), @@ -2909,10 +2740,10 @@ Example — add a signature image and a stamp, then screenshot to verify: RESOURCE_URI, { mimeType: RESOURCE_MIME_TYPE }, async (): Promise => { - const html = (cachedAppHtml ??= await fs.promises.readFile( + const html = await fs.promises.readFile( path.join(DIST_DIR, "mcp-app.html"), "utf-8", - )); + ); return { contents: [ { diff --git a/examples/pdf-server/src/annotation-panel.ts b/examples/pdf-server/src/annotation-panel.ts index 9fd4457..6b41095 100644 --- a/examples/pdf-server/src/annotation-panel.ts +++ b/examples/pdf-server/src/annotation-panel.ts @@ -289,23 +289,10 @@ function panelFieldNames(): Set { return new Set([...formFieldValues.keys(), ...pdfBaselineFormValues.keys()]); } -/** Baseline annotations the user has deleted. Shown crossed-out in the panel - * (mirroring cleared form fields) so they can be reverted, and so save knows - * to strip their refs from /Annots. */ -function removedBaselineAnnotations(): PdfAnnotationDef[] { - return deps - .state() - .pdfBaselineAnnotations.filter((a) => !annotationMap.has(a.id)); -} - /** Total count of annotations + form fields for the sidebar badge. * Uses the union so cleared baseline items still contribute. */ function sidebarItemCount(): number { - return ( - annotationMap.size + - removedBaselineAnnotations().length + - panelFieldNames().size - ); + return annotationMap.size + panelFieldNames().size; } export function updateAnnotationsBadge(): void { @@ -351,8 +338,6 @@ export function getAnnotationLabel(def: PdfAnnotationDef): string { return "Line"; case "image": return "Image"; - case "imported": - return `${def.subtype} (from PDF)`; } } @@ -396,8 +381,6 @@ export function getAnnotationColor(def: PdfAnnotationDef): string { return "#333"; case "image": return "#999"; - case "imported": - return "#666"; } } @@ -442,14 +425,6 @@ export function renderAnnotationPanel(): void { byPage.get(page)!.push(tracked); } - // Removed baseline annotations: still listed (crossed-out) so they can be - // reverted before save strips them from the file. - const removedByPage = new Map(); - for (const def of removedBaselineAnnotations()) { - if (!removedByPage.has(def.page)) removedByPage.set(def.page, []); - removedByPage.get(def.page)!.push(def); - } - // Group form fields by page — iterate the UNION so cleared baseline // fields remain visible (crossed out) with a per-item revert button. const fieldsByPage = new Map(); @@ -466,11 +441,7 @@ export function renderAnnotationPanel(): void { } // Collect all pages that have annotations or form fields - const allPages = new Set([ - ...byPage.keys(), - ...removedByPage.keys(), - ...fieldsByPage.keys(), - ]); + const allPages = new Set([...byPage.keys(), ...fieldsByPage.keys()]); const sortedPages = [...allPages].sort((a, b) => a - b); // Sort annotations within each page by Y position (descending = top-first in PDF coords) @@ -495,9 +466,8 @@ export function renderAnnotationPanel(): void { const sectionKey = `page-${pageNum}`; const isOpen = panelState.openAccordionSection === sectionKey; const annotations = byPage.get(pageNum) ?? []; - const removed = removedByPage.get(pageNum) ?? []; const fields = fieldsByPage.get(pageNum) ?? []; - const itemCount = annotations.length + removed.length + fields.length; + const itemCount = annotations.length + fields.length; appendAccordionSection( `Page ${pageNum} (${itemCount})`, @@ -513,10 +483,6 @@ export function renderAnnotationPanel(): void { for (const tracked of annotations) { body.appendChild(createAnnotationCard(tracked)); } - // Then removed baseline annotations (crossed-out, revertable) - for (const def of removed) { - body.appendChild(createRemovedAnnotationCard(def)); - } }, ); } @@ -682,55 +648,6 @@ function createAnnotationCard(tracked: TrackedAnnotation): HTMLElement { return card; } -/** - * Card for a baseline annotation the user deleted: crossed-out, no select/ - * navigate (it has no DOM on the page anymore), revert button puts it back - * into `annotationMap` so it renders again and save leaves it in the file. - */ -function createRemovedAnnotationCard(def: PdfAnnotationDef): HTMLElement { - const card = document.createElement("div"); - card.className = "annotation-card annotation-card-cleared"; - card.dataset.annotationId = def.id; - - const row = document.createElement("div"); - row.className = "annotation-card-row"; - - const swatch = document.createElement("div"); - swatch.className = "annotation-card-swatch annotation-card-swatch-cleared"; - swatch.innerHTML = ``; - row.appendChild(swatch); - - const typeLabel = document.createElement("span"); - typeLabel.className = "annotation-card-type"; - typeLabel.textContent = getAnnotationLabel(def); - row.appendChild(typeLabel); - - const preview = getAnnotationPreview(def); - if (preview) { - const previewEl = document.createElement("span"); - previewEl.className = "annotation-card-preview"; - previewEl.textContent = preview; - row.appendChild(previewEl); - } - - const revertBtn = document.createElement("button"); - revertBtn.className = "annotation-card-delete"; - revertBtn.title = "Restore annotation from file"; - revertBtn.innerHTML = REVERT_SVG; - revertBtn.addEventListener("click", (e) => { - e.stopPropagation(); - annotationMap.set(def.id, { def: { ...def }, elements: [] }); - updateAnnotationsBadge(); - renderAnnotationPanel(); - deps.renderPage(); - deps.persistAnnotations(); - }); - row.appendChild(revertBtn); - - card.appendChild(row); - return card; -} - /** Revert one field to its PDF-stored baseline value. */ function revertFieldToBaseline(name: string): void { const base = pdfBaselineFormValues.get(name); @@ -914,15 +831,8 @@ function clearFieldInStorage(name: string): void { meta?.[0]?.defaultValue ?? ""; const type = meta?.find((f) => f.type)?.type; - // Radio: per-widget BOOLEANS, never a string. pdf.js's - // RadioButtonWidgetAnnotation render() has inverted string coercion (see - // setFieldInStorage), so writing the same string to every widget checks - // the wrong one. {value:false} on all = nothing selected. - if (type === "radiobutton") { - for (const id of ids) storage.setValue(id, { value: false }); - return; - } - const clearValue = type === "checkbox" ? (dv ?? "Off") : (dv ?? ""); + const clearValue = + type === "checkbox" || type === "radiobutton" ? (dv ?? "Off") : (dv ?? ""); for (const id of ids) storage.setValue(id, { value: clearValue }); } diff --git a/examples/pdf-server/src/commands.ts b/examples/pdf-server/src/commands.ts index 6d27edf..c469ebd 100644 --- a/examples/pdf-server/src/commands.ts +++ b/examples/pdf-server/src/commands.ts @@ -66,5 +66,4 @@ export type PdfCommand = getScreenshots: boolean; } | { type: "save_as"; requestId: string } - | { type: "get_viewer_state"; requestId: string } | { type: "file_changed"; mtimeMs: number }; diff --git a/examples/pdf-server/src/mcp-app.css b/examples/pdf-server/src/mcp-app.css index a87dbcd..b6bbb43 100644 --- a/examples/pdf-server/src/mcp-app.css +++ b/examples/pdf-server/src/mcp-app.css @@ -227,10 +227,6 @@ body { align-items: flex-start; padding: 1rem; background: var(--bg200); - /* JS owns pinch (inline pinch-in → fullscreen). pan-x/pan-y keeps native - * scrolling; the fullscreen rule below repeats this with a comment on the - * iOS-Safari preventDefault backstop. */ - touch-action: pan-x pan-y; } .page-wrapper { @@ -314,20 +310,9 @@ body { } .main.fullscreen .toolbar { - /* Hosts wrap fullscreen in their own header (title + close), which already - * clears the top safe-area — so no --safe-top here, only sides. */ - padding: 0.25rem calc(0.5rem + var(--safe-right, 0px)) 0.25rem - calc(0.5rem + var(--safe-left, 0px)); - min-height: 40px; - /* Inline can wrap (narrow chat bubble); fullscreen has the width, and - * wrapping would double the bar height + desync the search-bar offset. */ - flex-wrap: nowrap; -} - -.main.fullscreen .search-bar { - /* -1px overlaps the toolbar border so the dropdown looks attached. */ - top: 39px; - right: calc(var(--safe-right, 0px) - 1px); + padding-top: calc(0.5rem + var(--safe-top, 0px)); + padding-left: calc(0.5rem + var(--safe-left, 0px)); + padding-right: calc(0.5rem + var(--safe-right, 0px)); } .main.fullscreen .viewer { @@ -590,21 +575,6 @@ body { user-select: none; } -/* Annotation imported verbatim from the PDF (Stamp/Ink/etc. via - * annotationCanvasMap). The body is the rasterized appearance canvas; - * if pdf.js didn't divert it (no hasOwnCanvas), the box stays transparent - * over the main-canvas pixel and just captures clicks. */ -.annotation-imported { - position: absolute; - pointer-events: auto; - cursor: grab; - user-select: none; -} -.annotation-imported:hover { - outline: 1px dashed var(--accent, #2563eb); - outline-offset: 1px; -} - /* Selection visuals */ .annotation-selected { outline: 2px solid var(--accent, #2563eb); diff --git a/examples/pdf-server/src/mcp-app.ts b/examples/pdf-server/src/mcp-app.ts index 45e0c74..7e53959 100644 --- a/examples/pdf-server/src/mcp-app.ts +++ b/examples/pdf-server/src/mcp-app.ts @@ -12,11 +12,8 @@ import { applyDocumentTheme, applyHostStyleVariables, } from "@modelcontextprotocol/ext-apps"; -import type { - CallToolResult, - ContentBlock, -} from "@modelcontextprotocol/client"; -import { z } from "zod"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { ContentBlock } from "@modelcontextprotocol/sdk/spec.types.js"; import * as pdfjsLib from "pdfjs-dist"; import { AnnotationLayer, AnnotationMode, TextLayer } from "pdfjs-dist"; import "pdfjs-dist/web/pdf_viewer.css"; @@ -28,17 +25,14 @@ import { type LineAnnotation, type StampAnnotation, type ImageAnnotation, - type ImportedAnnotation, type NoteAnnotation, type FreetextAnnotation, - cssColorToRgb, serializeDiff, deserializeDiff, mergeAnnotations, computeDiff, isDiffEmpty, buildAnnotatedPdfBytes, - parseAnnotationRef, importPdfjsAnnotation, uint8ArrayToBase64, convertFromModelCoords, @@ -152,11 +146,6 @@ const imageCache = new Map(); /** Annotations imported from the PDF file (baseline for diff computation). */ let pdfBaselineAnnotations: PdfAnnotationDef[] = []; -/** Pages whose native annotations have already been imported into the baseline. */ -const baselineScannedPages = new Set(); -/** Native-annotation ids the user deleted (from restored localStorage diff) — - * the lazy per-page scan must NOT re-add these to annotationMap. */ -const restoredRemovedIds = new Set(); // Dirty flag — tracks unsaved local changes let isDirty = false; @@ -352,11 +341,6 @@ async function refitScale(): Promise { // needs height changes too (rotation, browser chrome on mobile). let lastContainerW = 0; let lastContainerH = 0; -/** One-shot: refit on the next resize even if it's a shrink in inline mode. - * Set on fullscreen→inline so the page snaps to the new (smaller) width - * once the host has actually resized the iframe — the inline `grewW` gate - * would otherwise swallow that shrink. */ -let forceNextResizeRefit = false; const containerResizeObserver = new ResizeObserver(([entry]) => { const { width: w, height: h } = entry.contentRect; const grewW = w > lastContainerW + 1; @@ -364,12 +348,7 @@ const containerResizeObserver = new ResizeObserver(([entry]) => { Math.abs(w - lastContainerW) > 1 || Math.abs(h - lastContainerH) > 1; lastContainerW = w; lastContainerH = h; - if (forceNextResizeRefit && changed) { - forceNextResizeRefit = false; - refitScale(); - } else if (currentDisplayMode === "fullscreen" ? changed : grewW) { - refitScale(); - } + if (currentDisplayMode === "fullscreen" ? changed : grewW) refitScale(); }); containerResizeObserver.observe(canvasContainerEl as HTMLElement); @@ -1393,10 +1372,6 @@ const DRAGGABLE_TYPES = new Set([ "stamp", "note", "image", - // "imported" is draggable in the UI but the move does NOT persist to the - // PDF on save (addAnnotationDicts skips it). Resize/rotate stay disabled - // — the appearance bitmap would just stretch. - "imported", ]); function setupAnnotationInteraction( @@ -1904,25 +1879,6 @@ function paintAnnotationsOnCanvas( } break; } - - case "imported": { - const s = pdfRectToScreen( - { x: def.x, y: def.y, width: def.width, height: def.height }, - viewport, - ); - const bmp = annotationCanvasMap.get(def.pdfjsId); - ctx.save(); - if (bmp) { - ctx.drawImage(bmp, s.left, s.top, s.width, s.height); - } else { - ctx.strokeStyle = "#666"; - ctx.lineWidth = 1; - ctx.setLineDash([3, 3]); - ctx.strokeRect(s.left, s.top, s.width, s.height); - } - ctx.restore(); - break; - } } } } @@ -1977,20 +1933,13 @@ function renderAnnotation( viewport: { width: number; height: number; scale: number }, ): HTMLElement[] { switch (def.type) { - case "highlight": { - // Force translucency: def.color is an opaque hex (e.g. "#ffff00"), which - // would override the rgba()/mix-blend-mode in CSS and hide the text. - const rgb = def.color ? cssColorToRgb(def.color) : null; - const bg = rgb - ? `rgba(${Math.round(rgb.r * 255)}, ${Math.round(rgb.g * 255)}, ${Math.round(rgb.b * 255)}, 0.35)` - : undefined; + case "highlight": return renderRectsAnnotation( def.rects, "annotation-highlight", viewport, - bg ? { background: bg } : {}, + def.color ? { background: def.color } : {}, ); - } case "underline": return renderRectsAnnotation( def.rects, @@ -2020,8 +1969,6 @@ function renderAnnotation( return [renderLineAnnotation(def, viewport)]; case "image": return [renderImageAnnotation(def, viewport)]; - case "imported": - return [renderImportedAnnotation(def, viewport)]; } } @@ -2210,45 +2157,6 @@ function renderImageAnnotation( return el; } -/** - * Per-annotation appearance bitmaps from page.render(). Keyed by pdf.js - * annotation id (e.g. "118R"). Populated for the current page only — - * cleared at the start of each renderPage(). - */ -const annotationCanvasMap = new Map(); - -function renderImportedAnnotation( - def: ImportedAnnotation, - viewport: { width: number; height: number; scale: number }, -): HTMLElement { - const screen = pdfRectToScreen( - { x: def.x, y: def.y, width: def.width, height: def.height }, - viewport, - ); - const el = document.createElement("div"); - el.className = "annotation-imported"; - el.style.left = `${screen.left}px`; - el.style.top = `${screen.top}px`; - el.style.width = `${screen.width}px`; - el.style.height = `${screen.height}px`; - el.title = `${def.subtype} (from PDF)`; - - // page.render() may or may not have produced a separate canvas for this - // annotation (hasOwnCanvas depends on the PDF's flags). When it did, use - // it as a pixel-faithful body; when it didn't, the appearance is on the - // main canvas already, so leave the box transparent — it still captures - // clicks for select/delete. - const canvas = annotationCanvasMap.get(def.pdfjsId); - if (canvas) { - canvas.style.width = "100%"; - canvas.style.height = "100%"; - canvas.style.display = "block"; - canvas.style.pointerEvents = "none"; - el.appendChild(canvas); - } - return el; -} - // ============================================================================= // Annotation CRUD // ============================================================================= @@ -2502,99 +2410,17 @@ async function renderPageOffscreen(pageNum: number): Promise { return dataUrl.split(",")[1]; } -/** - * Snapshot the live viewer for `interact({action:"get_viewer_state"})`. - * - * Selection is read from `window.getSelection()` at call time — no caching; - * if the user navigated away or nothing is selected, `selection` is `null`. - * `boundingRect` is in model coords (PDF points, origin top-left, y-down) so - * it can be fed straight back into `add_annotations`. - */ -async function handleGetViewerState(requestId: string): Promise { - const CONTEXT_CHARS = 200; - - let selection: { - text: string; - contextBefore: string; - contextAfter: string; - boundingRect: { x: number; y: number; width: number; height: number }; - } | null = null; - - const sel = window.getSelection(); - const selectedText = sel?.toString().replace(/\s+/g, " ").trim(); - if (sel && selectedText && sel.rangeCount > 0) { - // Only treat it as a PDF selection if it lives inside the text layer of - // the rendered page (not the toolbar, search box, etc.). - const range = sel.getRangeAt(0); - const anchor = - range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE - ? (range.commonAncestorContainer as Element) - : range.commonAncestorContainer.parentElement; - if (anchor && textLayerEl.contains(anchor)) { - // Context: locate selection in the page's extracted text and slice - // ±CONTEXT_CHARS around it. Falls back to empty strings if fuzzy - // match fails (still return text + rect — they're the load-bearing - // bits). - const pageText = pageTextCache.get(currentPage) ?? ""; - const loc = findSelectionInText(pageText, selectedText); - const contextBefore = loc - ? pageText.slice(Math.max(0, loc.start - CONTEXT_CHARS), loc.start) - : ""; - const contextAfter = loc - ? pageText.slice(loc.end, loc.end + CONTEXT_CHARS) - : ""; - - // Single bounding box, page-relative model coords. getBoundingClientRect - // is viewport-relative; subtract the page-wrapper origin then divide by - // scale → PDF points (top-left origin, y-down — matches the coord - // system documented in the interact tool description). - const r = range.getBoundingClientRect(); - const origin = pageWrapperEl.getBoundingClientRect(); - const round = (n: number) => Math.round(n * 100) / 100; - selection = { - text: selectedText, - contextBefore, - contextAfter, - boundingRect: { - x: round((r.left - origin.left) / scale), - y: round((r.top - origin.top) / scale), - width: round(r.width / scale), - height: round(r.height / scale), - }, - }; - } - } - - const state = { - currentPage, - pageCount: totalPages, - zoom: Math.round(scale * 100), - displayMode: currentDisplayMode, - selectedAnnotationIds: [...selectedAnnotationIds], - selection, - }; - - await app.callServerTool({ - name: "submit_viewer_state", - arguments: { requestId, state: JSON.stringify(state, null, 2) }, - }); -} - -/** - * Collect text and/or screenshots for a set of page intervals. - * Shared by the server-driven `get_pages` command (via handleGetPages) - * and the app-registered `get_text` / `get_screenshot` tools. - */ -async function collectPageData( - intervals: Array<{ start?: number; end?: number }>, - getText: boolean, - getScreenshots: boolean, -): Promise> { - const allPages = expandIntervals(intervals); +async function handleGetPages(cmd: { + requestId: string; + intervals: Array<{ start?: number; end?: number }>; + getText: boolean; + getScreenshots: boolean; +}): Promise { + const allPages = expandIntervals(cmd.intervals); const pages = allPages.slice(0, MAX_GET_PAGES); log.info( - `collectPageData: ${pages.length} pages (${pages[0]}..${pages[pages.length - 1]}), text=${getText}, screenshots=${getScreenshots}`, + `get_pages: ${pages.length} pages (${pages[0]}..${pages[pages.length - 1]}), text=${cmd.getText}, screenshots=${cmd.getScreenshots}`, ); const results: Array<{ @@ -2608,7 +2434,7 @@ async function collectPageData( page: pageNum, }; - if (getText) { + if (cmd.getText) { // Use cached text if available, otherwise extract on the fly let text = pageTextCache.get(pageNum); if (text == null && pdfDocument) { @@ -2621,7 +2447,7 @@ async function collectPageData( pageTextCache.set(pageNum, text); } catch (err) { log.error( - `collectPageData: text extraction failed for page ${pageNum}:`, + `get_pages: text extraction failed for page ${pageNum}:`, err, ); text = ""; @@ -2630,35 +2456,17 @@ async function collectPageData( entry.text = text ?? ""; } - if (getScreenshots) { + if (cmd.getScreenshots) { try { entry.image = await renderPageOffscreen(pageNum); } catch (err) { - log.error( - `collectPageData: screenshot failed for page ${pageNum}:`, - err, - ); + log.error(`get_pages: screenshot failed for page ${pageNum}:`, err); } } results.push(entry); } - return results; -} - -async function handleGetPages(cmd: { - requestId: string; - intervals: Array<{ start?: number; end?: number }>; - getText: boolean; - getScreenshots: boolean; -}): Promise { - const results = await collectPageData( - cmd.intervals, - cmd.getText, - cmd.getScreenshots, - ); - // Submit results back to server try { await app.callServerTool({ @@ -2686,60 +2494,52 @@ function annotationStorageKey(): string | null { } /** - * Import one page's native annotations into the baseline. Called lazily from - * renderPage() so we don't walk every page (and pull most of the file via - * range requests) before the user sees anything. Idempotent per page. + * Import annotations from the loaded PDF to establish the baseline. + * These are the annotations that exist in the PDF file itself. */ -function scanPageBaselineAnnotations( - pageNum: number, - annotations: unknown[], -): void { - if (baselineScannedPages.has(pageNum)) return; - baselineScannedPages.add(pageNum); - let imported = 0; - for (let i = 0; i < annotations.length; i++) { - // Isolate each annotation: a malformed one must not bubble up to the - // caller's form-layer try in renderPage() (which would skip - // AnnotationLayer.render and hide form widgets for the whole page). +async function loadBaselineAnnotations( + doc: pdfjsLib.PDFDocumentProxy, +): Promise { + pdfBaselineAnnotations = []; + for (let pageNum = 1; pageNum <= doc.numPages; pageNum++) { try { - const ann = annotations[i] as { - annotationType?: number; - subtype?: string; - name?: string; - rect?: number[]; - }; - const def = importPdfjsAnnotation(ann, pageNum, i); - if (def) { - pdfBaselineAnnotations.push(def); - imported++; - if (!annotationMap.has(def.id) && !restoredRemovedIds.has(def.id)) { - annotationMap.set(def.id, { def, elements: [] }); + const page = await doc.getPage(pageNum); + const annotations = await page.getAnnotations(); + for (let i = 0; i < annotations.length; i++) { + const ann = annotations[i]; + const def = importPdfjsAnnotation(ann, pageNum, i); + if (def) { + pdfBaselineAnnotations.push(def); + // Add to annotationMap if not already present (from localStorage restore) + if (!annotationMap.has(def.id)) { + annotationMap.set(def.id, { def, elements: [] }); + } + } else if (ann.annotationType !== 20) { + // Widget (type 20) is expected to be skipped; anything else we + // don't import will still be painted by page.render() onto the + // canvas as unselectable pixels. Log so we can diagnose + // "ghost annotations" (visible but not in panel, not clickable). + log.info( + `[WARN] Baseline: skipped PDF annotation on page ${pageNum}`, + `type=${ann.annotationType}`, + `subtype=${ann.subtype ?? "?"}`, + `name=${ann.name ?? "?"}`, + `rect=${ann.rect ? JSON.stringify(ann.rect) : "none"}`, + ); } - } else if (ann.annotationType !== 20) { - // Widget (type 20) is expected to be skipped; anything else we - // don't import will still be painted by page.render() onto the - // canvas as unselectable pixels. Log so we can diagnose - // "ghost annotations" (visible but not in panel, not clickable). - log.info( - `[WARN] Baseline: skipped PDF annotation on page ${pageNum}`, - `type=${ann.annotationType}`, - `subtype=${ann.subtype ?? "?"}`, - `name=${ann.name ?? "?"}`, - `rect=${ann.rect ? JSON.stringify(ann.rect) : "none"}`, - ); } } catch (err) { - log.info(`Baseline: page ${pageNum} annotation import failed`, err); - } - } - if (imported > 0) { - try { - updateAnnotationsBadge(); - renderAnnotationPanel(); - } catch (err) { - log.info(`Baseline: page ${pageNum} panel update failed`, err); + // Log the error — a thrown import for one annotation silently + // drops the REST of that page's annotations too. + log.info( + `[WARN] Baseline: page ${pageNum} annotation import failed:`, + err, + ); } } + log.info( + `Loaded ${pdfBaselineAnnotations.length} baseline annotations from PDF`, + ); } function persistAnnotations(): void { @@ -2755,20 +2555,6 @@ function persistAnnotations(): void { pdfBaselineFormValues, ); - // computeDiff only sees baseline ids from pages we've already scanned. - // Carry forward restored tombstones for unvisited pages so the first - // persist after restore doesn't drop them. Once every page is scanned the - // baseline is complete and computeDiff is authoritative on its own — - // dropping the carry-forward then also stops a stale id (no longer in the - // file) from pinning dirty=true forever. - if (baselineScannedPages.size < totalPages) { - for (const id of restoredRemovedIds) { - if (!annotationMap.has(id) && !diff.removed.includes(id)) { - diff.removed.push(id); - } - } - } - // Dirty tracks whether there are unsaved changes. Undoing back to baseline // yields an empty diff → clean again → save button disables. if (!isRestoring) setDirty(!isDiffEmpty(diff)); @@ -2794,11 +2580,11 @@ function restoreAnnotations(): void { const diff = deserializeDiff(raw); // Merge baseline + diff. The loop below is add-only, so we MUST also - // delete: the per-page baseline scan re-seeds annotationMap with every - // native id it encounters — including ones in diff.removed. Without the - // deletes here AND the restoredRemovedIds tombstones below, the zombie - // survives, and the next persistAnnotations() sees it in currentIds → - // computeDiff produces removed=[] → the deletion is permanently lost. + // delete: loadBaselineAnnotations() runs between the two restore calls + // and re-seeds annotationMap with every baseline id — including the + // ones in diff.removed. Without this, the zombie survives the restore, + // and the next persistAnnotations() sees it in currentIds → computeDiff + // produces removed=[] → the deletion is permanently lost from storage. const merged = mergeAnnotations(pdfBaselineAnnotations, diff); for (const def of merged) { if (!annotationMap.has(def.id)) { @@ -2807,9 +2593,6 @@ function restoreAnnotations(): void { } for (const id of diff.removed) { annotationMap.delete(id); - // Tombstone so the lazy per-page baseline scan (which runs AFTER this - // restore) doesn't resurrect it. - restoredRemovedIds.add(id); } // Restore form fields @@ -2882,8 +2665,7 @@ function normaliseFieldValue( */ async function buildFieldNameMap( doc: pdfjsLib.PDFDocumentProxy, -): Promise { - let pushedToStorage = false; +): Promise { fieldNameToIds.clear(); radioButtonValues.clear(); fieldNameToPage.clear(); @@ -2901,14 +2683,6 @@ async function buildFieldNameMap( // getFieldObjects may fail on some PDFs } - // No AcroForm → nothing to map. Skip the per-page widget walk so form-free - // PDFs (the common large case) don't pull every page after first paint. - // getFieldObjects() itself only reads the catalog/AcroForm dict via range - // transport, so this gate is cheap. - if (!cachedFieldObjects || Object.keys(cachedFieldObjects).length === 0) { - return false; - } - // Scan every page's widget annotations to collect the CORRECT storage keys, // plus labels, pages, positions, AND fieldValue (what the widget renders // — which can differ from getFieldObjects().value if the PDF is internally @@ -2987,16 +2761,12 @@ async function buildFieldNameMap( if (!widgetIds) continue; // no widget → not rendered anyway // Type comes from getFieldObjects (widget annot data doesn't have it). - // Value: prefer the AcroForm field-tree value over the widget's - // fieldValue. pdf-lib's save() can leave a page widget pointing at a - // stale /V while the field tree has the new one (seen with comb text - // fields), and getAnnotations() reads the widget. If the two disagree - // we push the field-tree value into annotationStorage so the rendered - // input matches what's actually in /AcroForm. + // Value comes from the widget annotation (fall back to field-dict if + // the widget didn't expose one). const type = fieldArr.find((f) => f.type)?.type; - const fieldTreeRaw = fieldArr.find((f) => f.value != null)?.value; - const widgetRaw = widgetFieldValues.get(name); - const raw = fieldTreeRaw ?? widgetRaw; + const raw = widgetFieldValues.has(name) + ? widgetFieldValues.get(name) + : fieldArr.find((f) => f.value != null)?.value; const v = normaliseFieldValue(type, raw); if (v !== null) { pdfBaselineFormValues.set(name, v); @@ -3004,13 +2774,6 @@ async function buildFieldNameMap( // restored localStorage diff (applied in restoreAnnotations) will // overwrite specific fields the user changed. if (!formFieldValues.has(name)) formFieldValues.set(name, v); - // Widget out of sync with field tree → force storage so - // AnnotationLayer renders the field-tree value, not the stale - // widget. (syncFormValuesToStorage skips baseline==current.) - if (fieldTreeRaw != null && fieldTreeRaw !== widgetRaw) { - setFieldInStorage(name, v); - pushedToStorage = true; - } } // Skip parent entries with no concrete id (radio groups: the /T tree @@ -3025,7 +2788,6 @@ async function buildFieldNameMap( } log.info(`Built field name map: ${fieldNameToIds.size} fields`); - return pushedToStorage; } /** @@ -3113,39 +2875,15 @@ async function getAnnotatedPdfBytes(): Promise { } } - // Baseline annotations the user deleted: strip their refs from /Annots so - // they don't reappear on reload. Include restored tombstones for pages we - // haven't scanned yet — those ids aren't in pdfBaselineAnnotations but the - // ref is still parseable from the id string. Ids without a recoverable ref - // (page-index fallback) can't be removed by-ref and are skipped. - const removedIds = new Set(); - for (const a of pdfBaselineAnnotations) { - if (!annotationMap.has(a.id)) removedIds.add(a.id); - } - for (const id of restoredRemovedIds) { - if (!annotationMap.has(id)) removedIds.add(id); - } - const removedRefs = [...removedIds] - .map(parseAnnotationRef) - .filter((r): r is NonNullable => r !== null); - - // Only write fields that actually changed vs. what's already in the PDF. - // Unchanged fields are no-ops at best, and at worst trip pdf-lib edge - // cases (max-length text, missing /Yes appearance, …) on fields the user - // never touched — which, before the per-field catch in - // buildAnnotatedPdfBytes, aborted every subsequent field. - // - // Fields the user cleared (present in baseline, absent from formFieldValues - // after clearAllItems()) still need an explicit "" / false so pdf-lib - // overwrites the original /V instead of leaving it intact. - const formFieldsOut = new Map(); - for (const [name, value] of formFieldValues) { - if (pdfBaselineFormValues.get(name) !== value) { - formFieldsOut.set(name, value); - } - } + // buildAnnotatedPdfBytes gates on formFields.size > 0 and only writes + // entries present in the map. After clearAllItems() the map is empty → + // zero setText/uncheck calls → pdf-lib leaves original /V intact → + // the "stripped PDF" we promised keeps all its form data. To actually + // clear, send an explicit sentinel for every baseline field the user + // dropped: "" for text, false for checkbox (matching baseline type). + const formFieldsOut = new Map(formFieldValues); for (const [name, baselineValue] of pdfBaselineFormValues) { - if (!formFieldValues.has(name)) { + if (!formFieldsOut.has(name)) { formFieldsOut.set(name, typeof baselineValue === "boolean" ? false : ""); } } @@ -3153,7 +2891,6 @@ async function getAnnotatedPdfBytes(): Promise { fullBytes as Uint8Array, annotations, formFieldsOut, - removedRefs, ); } @@ -3195,6 +2932,15 @@ async function savePdf(): Promise { const sc = result.structuredContent as { mtimeMs?: number } | undefined; lastSavedMtime = sc?.mtimeMs ?? null; + // Rebase: the file on disk now contains our annotations + form values. + // Update the baseline so future diffs are relative to what was saved. + pdfBaselineAnnotations = [...annotationMap.values()].map((t) => ({ + ...t.def, + })); + pdfBaselineFormValues.clear(); + for (const [k, v] of formFieldValues) pdfBaselineFormValues.set(k, v); + + setDirty(false); // → updateSaveBtn() disables button const key = annotationStorageKey(); if (key) { try { @@ -3203,13 +2949,6 @@ async function savePdf(): Promise { /* ignore */ } } - // Reload from the bytes we just wrote. The previous approach (rebase - // baselines but keep the old pdfDocument) drifts: subsequent renders - // still rasterize stripped annotations from the old bytes, and the - // field/widget split that pdf-lib's save can create isn't reflected - // until reload anyway. Reload makes "what you see = what's on disk" - // an invariant. (file_changed echo is suppressed by lastSavedMtime.) - await reloadPdf(); } } catch (err) { log.error("Save failed:", err); @@ -3313,15 +3052,8 @@ async function renderPage() { // resize so the size handoff is atomic. pageWrapperEl.style.transform = ""; - // Retina: pass dpr via page.render's `transform` (NOT ctx.scale). - // pdf.js sizes per-annotation canvases as - // width = rectW * outputScaleX * viewport.scale - // and outputScaleX is read from transform[0] (defaults to 1). A bare - // ctx.scale(dpr,dpr) leaves outputScaleX at 1, so the - // annotationCanvasMap canvases get a half-sized backing store on - // retina while their internal setTransform IS dpr-aware → the - // appearance renders 2× too big into a 1× buffer → cropped/shifted. - const dprTransform = dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined; + // Scale context for retina + ctx.scale(dpr, dpr); // Clear and setup text layer textLayerEl.innerHTML = ""; @@ -3330,29 +3062,11 @@ async function renderPage() { // Set --scale-factor so CSS font-size/transform rules work correctly. textLayerEl.style.setProperty("--scale-factor", `${scale}`); - // Render canvas - track the task so we can cancel it. - // - // annotationCanvasMap: pdf.js diverts annotations whose appearance needs - // its own bitmap (Stamp/Ink/FreeText/etc. with hasOwnCanvas) into - // per-id canvases instead of compositing onto the main canvas. - // renderImportedAnnotation() pulls from this map so those annotations - // become movable DOM elements with pixel-faithful visuals — instead of - // unselectable canvas pixels (the old "ghost annotation" problem) or - // our lossy text-label re-render. - annotationCanvasMap.clear(); + // Render canvas - track the task so we can cancel it // eslint-disable-next-line @typescript-eslint/no-explicit-any const renderTask = (page.render as any)({ canvasContext: ctx, viewport, - transform: dprTransform, - annotationCanvasMap, - // isEditing forces hasOwnCanvas=true for stamps regardless of /F - // NoRotate (StampAnnotation.mustBeViewedWhenEditing in pdf.worker). - // Without this, stamps without NoRotate composite onto the main canvas - // and deleting the "imported" overlay leaves an unclickable pixel - // behind. Other markup types still gate on noRotate; for those the - // overlay stays a transparent click-box (delete is UI-only until save). - isEditing: true, }); currentRenderTask = renderTask; @@ -3410,9 +3124,6 @@ async function renderPage() { formLayerEl.style.setProperty("--total-scale-factor", `${scale}`); try { const annotations = await page.getAnnotations(); - // Lazy baseline import — piggyback on the annotations we just fetched - // for this page instead of walking all pages upfront. - scanPageBaselineAnnotations(pageToRender, annotations); if (annotations.length > 0) { const linkService = { getDestinationHash: () => "#", @@ -3436,15 +3147,8 @@ async function renderPage() { commentManager: null, } as any); // eslint-disable-next-line @typescript-eslint/no-explicit-any - // Only feed Widgets (form fields) here. Markup annotations are - // owned by #annotation-layer; letting AnnotationLayer create - //
elements for them in #form-layer adds invisible - // pointer-events:auto boxes that steal clicks from our overlays. - const widgetAnns = annotations.filter( - (a: { subtype?: string }) => a.subtype === "Widget", - ); await annotationLayer.render({ - annotations: widgetAnns, + annotations, div: formLayerEl, page, viewport, @@ -3620,10 +3324,6 @@ function zoomIn() { function zoomOut() { userHasZoomed = true; - // Intentionally NOT floored at fit-to-page (unlike pinch). Hosts may - // overlay UI on the iframe without reporting it in safeAreaInsets, so - // "fit" can leave the page bottom hidden; the button is the escape hatch - // to shrink past it. Pinch still rubber-bands at fit (see commitPinch). scale = Math.max(scale - 0.25, ZOOM_MIN); renderPage().then(scrollSelectionIntoView); } @@ -3699,10 +3399,6 @@ formLayerEl.addEventListener("input", (e) => { if (!target.checked) return; // unchecking siblings — ignore const wid = target.getAttribute("data-element-id"); value = (wid && radioButtonValues.get(wid)) ?? target.value; - } else if (target instanceof HTMLSelectElement && target.multiple) { - // .value on a