diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ff02b54..91bcce9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,8 +39,8 @@ Each level catches what the one before cannot. It lists the bundled snapshot (`src/tools.json`), and every tool call answers that `BYTEBASE_URL` is not set. 3. **A real instance**: `scripts/check-live.mjs` starts the server as a client would, lists tools, - and runs two read-only calls. Signed out, the first list is empty and the browser sign-in opens - as soon as the server starts; the first call waits for it. + and runs two read-only calls. Signed out, the first list is the bundled snapshot and the browser + sign-in opens as soon as the server starts; the first call waits for it. ```bash BYTEBASE_URL=http://localhost:8080 BYTEBASE_MCP_HOME="$(mktemp -d)" node scripts/check-live.mjs @@ -140,13 +140,16 @@ The automated tests do not cover these: must honor `tools/list_changed`). - [ ] A confirmation form (for example approving an issue) left open for more than a minute can still be answered, and the answer reaches Bytebase. -- [ ] Clients not yet exercised: Cursor, Claude Desktop, Windsurf. Windows has never been run. +- [ ] In Claude Desktop, from a signed-out start through the config file: a Code-tab session lists + Bytebase's tools, the sign-in opens one browser tab, and Chat and the Code tab share it. +- [ ] Clients not yet exercised: Cursor, Windsurf. Windows has never been run. ## Keeping the snapshot current -`src/tools.json` is the tool list MCP directories see before an instance is configured; a -configured server never reads it. Before a release, regenerate it from an instance on the latest -Bytebase release, never a development build, so directories list no tool users cannot get yet: +`src/tools.json` is the tool list MCP directories see before an instance is configured, and the +list a configured server offers until its session opens. Before a release, regenerate it from an +instance on the latest Bytebase release, never a development build, so no one is shown a tool +users cannot get yet: ```bash npm run build diff --git a/README.md b/README.md index 327c64c..63e44b9 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Every command takes `--url ` in place of `BYTEBASE_URL`. ## Tools -Once you sign in, the tools are the ones your instance serves, so an older or newer Bytebase shows its own. The table below is a snapshot, the list MCP directories see before any instance is configured: +Once you sign in, the tools are the ones your instance serves, so an older or newer Bytebase shows its own. The table below is the bundled snapshot. MCP directories show it when no instance is configured, and your client shows it until you sign in: Generated from Bytebase 3.25.0. @@ -106,10 +106,10 @@ Generated from Bytebase 3.25.0. ## How it works -1. With `BYTEBASE_URL` set, the server answers `initialize` at once. If you have signed in before, it opens a session first and passes on your instance's own instructions; otherwise it starts the browser sign-in, and announces your instance's tools with `tools/list_changed` once you have signed in. +1. With `BYTEBASE_URL` set, the server answers `initialize` at once. If you have signed in before, it opens a session first and passes on your instance's own instructions and tools. Otherwise it lists the bundled snapshot and starts the browser sign-in. A tool call made before then waits for the sign-in, or starts one. Once you have signed in, it announces your instance's own tools with `tools/list_changed`. 2. It connects to `/mcp` over Streamable HTTP. With no valid token it runs the OAuth authorization-code flow with PKCE: discovery through `/.well-known/oauth-protected-resource/mcp`, dynamic client registration, browser sign-in, loopback redirect. 3. Tool lists, tool calls, results and confirmation forms pass through unchanged, paging included. -4. Without `BYTEBASE_URL`, the server lists the bundled snapshot so MCP directories can show Bytebase's tools, and every tool call says to set `BYTEBASE_URL`. A configured server never uses the snapshot. +4. Without `BYTEBASE_URL`, the server lists the bundled snapshot so MCP directories can show Bytebase's tools, and every tool call says to set `BYTEBASE_URL`. A configured server lists the snapshot only until your session opens. The design, with every state the server can be in, is in [docs/DESIGN.md](docs/DESIGN.md). diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 73874dc..f2f5160 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,13 +1,13 @@ # Design: a proxy that gets Bytebase's tools from the instance -Status: proposal (revision 2) · 2026-11-22 · Linear BYT-10055 +Status: proposal (revision 3) · 2026-11-24 · Linear BYT-10055, BYT-10611 This package lets MCP directories and local-command clients use the MCP server built into every -Bytebase instance. **A configured proxy gets every tool and instruction from its Bytebase -instance, after sign-in. A snapshot of the tool list ships in the package for one purpose, -letting MCP directories list Bytebase when no instance is configured, and a configured proxy never -reads it.** This file replaces the first version's design notes (2026-11-16); the last sections -say what was kept and what changed. +Bytebase instance. **Once signed in, a configured proxy gets every tool and instruction from its +Bytebase instance. A snapshot of the tool list ships in the package. It lets MCP directories list +Bytebase when no instance is configured, and it is the tool list a configured proxy offers until +its session opens.** This file replaces the first version's design notes (2026-11-16); the last +sections say what was kept and what changed. ## Problem @@ -30,9 +30,9 @@ Users saw tools their instance did not have. ## Principle -> Users see only what their instance serves. The package adds transport, sign-in, the words for -> its own states, and a tool-list snapshot used only for directory listings. The one Bytebase rule -> it copies is when the form paragraph applies (D4). +> Signed-in users see only what their instance serves. The package adds transport, sign-in, the +> words for its own states, and a tool-list snapshot for directory listings and for the time before +> a session opens. The one Bytebase rule it copies is when the form paragraph applies (D4). ## Approaches weighed @@ -51,8 +51,16 @@ route on every instance. **D. No list before sign-in at all.** Simplest. Glama still lists the package, but with no tools and no quality grade: sign-in-first bridges such as a fork of `mcp-remote` show "Not graded" there. -**E. Snapshot for directories, instance for users (chosen).** Directories get the snapshot; users -never do. Drift can only age the directory listing, and a release refreshes it. +**E. Snapshot for directories, instance for users.** Directories get the snapshot; users never +do, so a configured proxy lists nothing until its session opens and then sends +`tools/list_changed`. Chosen in revision 2, replaced by F: Claude Desktop's Code and Cowork process +reads the list once, drops a server whose list is empty, and ignores `tools/list_changed` +(BYT-10611), so those sessions never got Bytebase's tools after a signed-out start. + +**F. Snapshot until the session opens, instance after (chosen).** As E, except a configured +proxy without a session lists the snapshot instead of nothing. Users can see drift, but only between +a signed-out start and the session opening, or until a client that ignores `tools/list_changed` +reconnects (D2). Prior art for the user side is `mcp-remote` (geelen/mcp-remote): it signs in before it connects, then passes `initialize`, `tools/list` and everything else through. Signing in before answering @@ -74,26 +82,40 @@ server, with a fresh `initialize`, so one process never changes state between un configured. Rejected: asking for the URL with form elicitation at first use. Few clients support it, and the client config already has an `env` block. It can come later. -**D2 · Where `tools/list` comes from depends on configuration, not on sign-in.** +**D2 · `tools/list` comes from the session once one has answered it, and from the snapshot +before.** - No URL configured: the snapshot (D3), in one page. - URL configured, session open: the session's `tools/list`. The client's `cursor` is passed to the instance and the instance's `nextCursor` back, so the instance pages its own list. -- URL configured, no session yet: an empty list. When a session opens, the proxy sends - `tools/list_changed`; afterwards it forwards the instance's own. - -Keying on sign-in instead would show the snapshot to a configured user before they sign in, which -is the drift this design removes. - -**D3 · The snapshot is generated from an instance and used only when no URL is configured.** +- URL configured, and no `tools/list` answered from a session yet in this process: the snapshot, in + one page. When the session opens, the proxy sends `tools/list_changed`; afterwards it forwards + the instance's own. +- URL configured, and a session answered before but has since dropped: reopened within a bound + (D5), then a JSON-RPC error. The client already holds the instance's list, and the snapshot would + replace it with an older one. + +A first list must not be empty. Claude Desktop's Code and Cowork process calls `tools/list` once +when it connects, drops a server whose list is empty, and never handles `tools/list_changed`, and +one connection serves all of those sessions. An empty first list hides Bytebase from them until +Desktop reconnects. The snapshot keeps the server, and the first tool call signs in (D5). + +Drift is the cost (D3). A client that honors `tools/list_changed` sees the snapshot only until its +session opens. One that ignores it keeps the snapshot until it reconnects. A start with a stored +sign-in opens the session inside `initialize` (D4) and never shows it. A call to a snapshot tool the +instance does not serve gets an error result that says so (rule 4). + +**D3 · The snapshot is generated from an instance and used until a session answers.** `src/tools.json` holds `bytebaseVersion`, `generatedAt`, `instructions` and `tools`. `npm run sync-tools` regenerates it before a release, against an instance on the latest Bytebase release, never a development build, so a directory lists no tool that users cannot get yet: it signs in as the package does, reads every page of `tools/list`, and strips the per-session parts of the instructions (the account line, and the paragraph Bytebase adds for clients without forms). -The README's tools table is rendered from it and labeled as a snapshot. A stale snapshot only ages -the directory listing, so a manual sync per release is enough; nothing checks it in CI, because -that would need an instance. +The README's tools table is rendered from it and labeled as a snapshot. A configured user sees +it until their session opens (D2), so an instance older than the snapshot's release shows tools it +lacks, and a newer one is missing its newest tools until then. A sync before each package release +keeps that gap to the instance's own age. Nothing checks it in CI, because that would need an +instance. **D4 · The initialize instructions are fixed when the client initializes.** MCP has no notification for changed instructions, so the proxy decides once, from its state at `initialize` @@ -105,7 +127,8 @@ notification for changed instructions, so the proxy decides once, from its state the instance writes the per-session account line and the form paragraph as for a direct connection. - Configured, no session (S3, S4): one fixed paragraph from the package that names the state and - what happens next. For a client whose elicitation capability is absent or names `url` without + what happens next, and says the listed tools are the package's snapshot until the session opens + (D2). For a client whose elicitation capability is absent or names `url` without `form`, it ends with the package's one-sentence version of the form paragraph (before running a statement that may write, show it to the user and ask them to confirm), because the instance's text cannot be read before sign-in. The rule copies the instance's own @@ -115,10 +138,10 @@ Opening the session and probing the instance are bounded at 5 seconds in total, startup timeout is not hit. **D5 · A configured proxy signs in right after the client initializes.** Without a session it -has no tools to offer, so the sign-in starts after the client's `initialized` notification, and a -tool call made before it finishes waits for it. A sign-in that fails or times out is not restarted -on its own, so a user who ignores it is not sent repeated browser tabs; a client restart starts it -again. When the instance cannot be reached (unreachable, as defined under States), opening the session is retried up to 10 times, waiting 1 +can only list the snapshot, so the sign-in starts after the client's `initialized` notification, +and a tool call made before it finishes waits for it. A sign-in that fails or times out is not +restarted on its own, so a user who ignores it is not sent repeated browser tabs; the next tool +call starts one, and so does a client restart. When the instance cannot be reached (unreachable, as defined under States), opening the session is retried up to 10 times, waiting 1 second and doubling to at most 5 minutes (about 14 minutes in all), then stops until the client restarts; the browser opens only once the instance answers. Only an opening that has not opened the browser is retried: once it has, any failure, unreachable included, is a failed sign-in. @@ -160,13 +183,30 @@ first version registered every session as one "Bytebase MCP (npm)" client. Conse client application signs in once per instance, as it would over a direct connection, and the `login` command goes away, since it has no client to sign in as. +One application can connect under more than one `clientInfo.name`. The proxy maps the names it +knows to one application (`clientIdentity` in `src/auth.ts`). A name it doesn't know is its own +application. + +| `clientInfo.name` | Who sends it | Sign-in (client key) | Consent name | +| - | - | - | - | +| `claude-ai` | Claude Desktop's Chat | `claude-ai` | Claude via Bytebase MCP | +| `local-agent-mode-` | Claude Desktop's Code tab and Cowork, one process for both | `claude-ai` | Claude via Bytebase MCP | +| `-era-probe` | Claude Desktop's startup probe, closed within a second | its own | its own | +| anything else | any other client | `clientInfo.name` | ` via Bytebase MCP` | + +Sharing Chat's sign-in lets the Code and Cowork process start in S2 with the instance's own list, +once the user has signed in through either. Before that, it lists the snapshot (D2) and signs in +itself; under the shared lock (D7), whichever process starts first opens the one browser tab, and +the other uses the sign-in it saves. The probe stays separate because it needs no tools, and a +shared sign-in would make it open a session on every launch. + **D7 · Tokens are stored per sign-in, and one lock guards every write.** One file per sign-in at `<home>/<instance key>/<client key>.json` (mode 0600, directory 0700), written to a temp file and renamed. `home` is `BYTEBASE_MCP_HOME`, by default `~/.bytebase-mcp`: these are credentials, not configuration, so not under `~/.config`, which people often sync or keep in dotfile repositories. The instance key is host, port and path, so two instances on one host -under different paths do not collide; the client key is `clientInfo.name` with characters outside -`[A-Za-z0-9._-]` replaced. Bytebase refresh tokens are single-use (`ConsumeOAuth2RefreshToken` in +under different paths do not collide; the client key is the application's key from D6, with +characters outside `[A-Za-z0-9._-]` replaced. Bytebase refresh tokens are single-use (`ConsumeOAuth2RefreshToken` in `backend/api/oauth2/token.go`), and clients start one proxy process per session, so several processes share one sign-in. Rules: @@ -205,7 +245,7 @@ under the lock and is then sent. **D8 · Versioning is independent of Bytebase.** The package has its own semver and works with any instance from 3.22, the first with MCP OAuth. The snapshot records the Bytebase version it was -read from (`bytebaseVersion`); that only describes the directory listing. `server.json` keeps +read from (`bytebaseVersion`); it describes the snapshot, not the instance a user connects to. `server.json` keeps following `package.json` (`scripts/sync-version.mjs`). **D9 · The commands are `serve`, `logout` and `status`.** `serve` (the default) is what clients @@ -228,21 +268,25 @@ Any other answer means not Bytebase. | --- | --- | --- | --- | | **S1** No URL configured | A one-line note (no Bytebase instance is connected; set `BYTEBASE_URL` to the instance's external URL in the client's config and restart), then the snapshot's instructions. | The snapshot's tools. | Error result with the same fix. Nothing is sent anywhere. | | **S2** Signed in | The instance's own, verbatim. | The session's, cursors passed through. | Forwarded. | -| **S3** Bytebase, no session | Fixed: names the instance; tools appear after signing in to Bytebase in the browser. Plus the form sentence (D4). | Empty until the session opens, then the session's, announced with `tools/list_changed`. | Waits for the sign-in, then forwards. | -| **S4** Unreachable, or not Bytebase | Fixed: names the URL and the reason. Unreachable gives the network error or the gateway's status; not Bytebase says to check that the value is the instance's external URL. Plus the form sentence (D4). | Empty; when a retried opening succeeds, as in S3. | Tries to open a session; on failure, an error result with the reason. | +| **S3** Bytebase, no session | Fixed: names the instance; sign in to Bytebase in the browser; the listed tools are the package's snapshot until then. Plus the form sentence (D4). | The snapshot's tools until the session opens, then the session's, announced with `tools/list_changed`. | Waits for the sign-in under way, or starts one, then forwards. | +| **S4** Unreachable, or not Bytebase | Fixed: names the URL and the reason. Unreachable gives the network error or the gateway's status; not Bytebase says to check that the value is the instance's external URL. Plus the form sentence (D4). | The snapshot's tools; when a retried opening succeeds, as in S3. | Tries to open a session; on failure, an error result with the reason. | Rules that hold in every state: -1. A configured proxy describes only tools it read from its instance in this process; the - snapshot is read only when no URL is configured. +1. Once a session has answered `tools/list`, a configured proxy describes only tools it read from + its instance in this process. Before that, it lists the snapshot (D2). 2. A proxy with a URL contacts only that instance. A proxy without one contacts nothing. 3. Readers take every page: `sync-tools` and the proxy's own reads follow `nextCursor` to the end. 4. Tool results, errors and elicitation requests from the instance pass through unchanged. The package's own errors on `tools/call` (S1, S4, failed sign-in) are tool results with `isError`, never JSON-RPC errors, so the model can read the fix. A `tools/list` the proxy cannot answer - from a reopened session gets a JSON-RPC error carrying the reason. The one addition to a - forwarded result: after a successful `reauthorize` (Bytebase's account-switch tool), the proxy - appends a note to reconnect this server and sign in as the account wanted. Instructions do not + from a reopened session gets a JSON-RPC error carrying the reason. Two answers from the + instance are changed. When it refuses a call with `unknown tool` (the Go SDK's error for a tool it + does not serve), the proxy answers with an error result instead. The result names the tool and + the snapshot's Bytebase version, and says to reconnect this server for the instance's own list: + the client got the name from the snapshot (D2). And after a successful `reauthorize` (Bytebase's + account-switch tool), the proxy appends a note to the result to reconnect this server and sign + in as the account wanted. Instructions do not change until the client reinitializes (D4), so reconnecting is what replaces any that named the old account. The note claims nothing about what the client's instructions say: the proxy cannot know whether they named an account (older Bytebase releases send none). @@ -285,9 +329,11 @@ protected-resource document, an OAuth server and an MCP endpoint built with the - Publishing to npm or the MCP registry, making the repository public, claiming the Glama listing. - Tool annotations on the server, which Glama's score and vendor preflights read. That is server work, and whether `query_database` gets static or mode-aware hints is still open. -- Checking which clients honor `tools/list_changed`. On a configured user's first run the tools - arrive with it after sign-in; a client that ignores it shows them only after a restart, when the - stored sign-in makes S2 immediate. Verify Cursor and Claude Desktop before 1.0. +- Checking which clients honor `tools/list_changed`. Claude Desktop's Chat does; its Code and + Cowork process does not (BYT-10611), and keeps the snapshot until Desktop reconnects. Verify + Cursor before 1.0. +- Whether Claude Desktop's tool-call timeout leaves time for a browser sign-in that the first call + starts. - Asking for the URL with elicitation (D1); headless sign-in (the loopback redirect cannot reach a headless machine anyway). - An npm snippet on the console's MCP page, and the client application's name in the audit table. @@ -297,7 +343,8 @@ protected-resource document, an OAuth server and an MCP endpoint built with the ## Kept from the first version - No tool logic in the package; results pass through untouched. -- The bundled `tools.json`, `sync-tools` and the README tools table, now for directory listings only. +- The bundled `tools.json`, `sync-tools` and the README tools table, for directory listings and the + time before a session opens. - OAuth, not a service-account token: `/mcp` accepts only its own OAuth tokens, bound to the external URL. - A fixed loopback port, because dynamic client registration stores the redirect URI with the @@ -315,7 +362,7 @@ protected-resource document, an OAuth server and an MCP endpoint built with the | First version | This version | Why | | --- | --- | --- | -| Every client got the bundled list until a live list arrived | Only an unconfigured proxy uses the snapshot; a configured one lists only its instance's tools | Users never see drift (D2) | +| Every client got the bundled list until a live list arrived | The snapshot until a session answers, then only the instance's tools; a call to a snapshot tool the instance lacks says so | A client that reads the list once still gets tools; drift ends when the session opens or the client reconnects (D2) | | Live list read once, first page only | Session's list with cursors passed through; every reader takes every page | Long lists and paging (D2, rule 3) | | Instructions from the bundle, or fallback text in the package | Signed in: the instance's own; otherwise package text for the state | D4 | | Background sign-in after the first `tools/list` | Sign-in after `initialized`, not restarted on its own after a failure | D5 | diff --git a/package-lock.json b/package-lock.json index 60ca652..3171427 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@bytebase/bytebase-mcp", - "version": "0.1.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@bytebase/bytebase-mcp", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "1.32.2" diff --git a/package.json b/package.json index 3743cae..4664c8d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bytebase/bytebase-mcp", - "version": "0.1.0", + "version": "0.1.1", "mcpName": "io.github.bytebase/bytebase-mcp", "description": "Official MCP server package for Bytebase. Reads the tool list from your Bytebase instance and forwards every call to its OAuth-protected /mcp endpoint.", "repository": { diff --git a/server.json b/server.json index d1840c6..cddc588 100644 --- a/server.json +++ b/server.json @@ -8,12 +8,12 @@ "source": "github" }, "websiteUrl": "https://docs.bytebase.com/integrations/mcp", - "version": "0.1.0", + "version": "0.1.1", "packages": [ { "registryType": "npm", "identifier": "@bytebase/bytebase-mcp", - "version": "0.1.0", + "version": "0.1.1", "transport": { "type": "stdio" }, diff --git a/src/auth.ts b/src/auth.ts index 97ef1e9..734f09c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -28,8 +28,12 @@ export interface ClientIdentity { clientName: string; } +/** Claude Desktop's Chat process and its Code-tab and Cowork process share one sign-in (D6). */ +const CLAUDE_DESKTOP: ClientIdentity = { key: "claude-ai", clientName: "Claude via Bytebase MCP" }; + export function clientIdentity(info: Implementation | undefined): ClientIdentity { const name = info?.name?.trim() || "unknown-client"; + if (name === "claude-ai" || name.startsWith("local-agent-mode-")) return CLAUDE_DESKTOP; const label = info?.title?.trim() || name; return { key: name.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 100), diff --git a/src/server.ts b/src/server.ts index bb4f80c..ec36525 100644 --- a/src/server.ts +++ b/src/server.ts @@ -74,21 +74,32 @@ function declaresForm(capabilities: ClientCapabilities | undefined): boolean { return Boolean(elicitation.form) || !elicitation.url; } +function snapshotNote(): string { + return `Until then, the tools listed are bytebase-mcp's snapshot of Bytebase ${loadBundledTools().bytebaseVersion}, which may differ from the instance's own.`; +} + /** S3 and S4: the package's paragraph for a configured proxy with no session. */ function signedOutInstructions(instance: string, probe: InstanceProbe, capabilities: ClientCapabilities | undefined): string { const text = probe.kind === "bytebase" - ? `Sign in to Bytebase at ${instance} in the browser window this server opens. Its tools appear once you have signed in.` + ? `Sign in to Bytebase at ${instance} in the browser window this server opens; the first tool call waits for the sign-in. ${snapshotNote()}` : probe.kind === "unreachable" - ? `The Bytebase instance at ${instance} could not be reached (${probe.detail}). Its tools appear once it can be reached and you have signed in.` - : `${instance} does not answer as a Bytebase instance (${probe.detail}). Check that BYTEBASE_URL is the instance's external URL (Settings > General > External URL).`; + ? `The Bytebase instance at ${instance} could not be reached (${probe.detail}). Its own tools are listed once it can be reached and you have signed in. ${snapshotNote()}` + : `${instance} does not answer as a Bytebase instance (${probe.detail}). Check that BYTEBASE_URL is the instance's external URL (Settings > General > External URL). The tools listed are bytebase-mcp's snapshot and cannot run until it is.`; return declaresForm(capabilities) ? text : `${text}\n\n${FORM_SENTENCE}`; } +/** Rule 4: the instance refused a tool name the client got from the snapshot (D2). */ +function unknownToolResult(name: string): CallToolResult { + const text = `Bytebase MCP: this Bytebase instance has no tool named "${name}". The tool list came from bytebase-mcp's snapshot of Bytebase ${loadBundledTools().bytebaseVersion}, listed before you signed in. Reconnect this MCP server to get the instance's own tools.`; + return { isError: true, content: [{ type: "text", text }] }; +} + /** * Builds the stdio MCP server. Without a URL it lists the bundled snapshot, - * for directory listings, and runs nothing; with one it lists only what the - * instance serves once a session is open (docs/DESIGN.md, D2). + * for directory listings, and runs nothing. With one it lists the snapshot + * until a session has answered tools/list, then only what the instance serves + * (docs/DESIGN.md, D2). */ export function createServer(config: Config): { server: Server; upstream: () => Upstream | undefined } { const server = new Server( @@ -100,6 +111,8 @@ export function createServer(config: Config): { server: Server; upstream: () => // client on this SDK would keep the first withdrawn form up (D5). (server as unknown as { _requestMessageId: number })._requestMessageId = 1; let initialized = false; + // Whether the client may still hold the snapshot as its tool list (D2). + let listedFromSession = false; // Created at initialize: a sign-in belongs to the client application (D6). let upstream: Upstream | undefined; @@ -146,7 +159,7 @@ export function createServer(config: Config): { server: Server; upstream: () => server.oninitialized = () => { initialized = true; - // A configured proxy without a session has no tools to offer, so it signs in now (D5). + // A configured proxy without a session can only list the snapshot, so it signs in now (D5). if (!config.url || upstream?.session) return; void signInWhenReachable(config.url); }; @@ -195,21 +208,23 @@ export function createServer(config: Config): { server: Server; upstream: () => server.setRequestHandler(ListToolsRequestSchema, async (request) => { if (!config.url) return { tools: loadBundledTools().tools }; - // Without a session there is nothing to list yet (D2), and tools/list never - // waits on a sign-in: the tools are announced when the session opens. With - // a stored sign-in and no sign-in under way, a session dropped by an outage + // Until a session has answered, the snapshot, never an empty list, and + // tools/list never waits on a sign-in: the instance's tools are announced + // when the session opens (D2). After that, a session dropped by an outage // is reopened here (D5), within a bound. const target = upstreamFor(config.url); - if (!target.session && (target.signingIn || !target.provider.hasStoredSignIn())) return { tools: [] }; + if (!target.session && !listedFromSession) return { tools: loadBundledTools().tools }; // Only a wait spent reopening a dropped session ends in an announcement; a // slow answer on an open session changes nothing the client holds. const reopening = !target.session; try { - return await withinBound((signal) => target.listTools(request.params?.cursor, signal), LIST_BOUND_MS, + const page = await withinBound((signal) => target.listTools(request.params?.cursor, signal), LIST_BOUND_MS, // The reconnect carries on; when it opens, the client is told to list again. () => { if (reopening) announceWhenOpen(target); }, `still connecting to ${config.url.toString().replace(/\/$/, "")}`); + listedFromSession = true; + return page; } catch (err) { if (err instanceof McpError) throw err; // tools/list has no error result, so the reason goes in a JSON-RPC error (rule 4). @@ -232,7 +247,13 @@ export function createServer(config: Config): { server: Server; upstream: () => } return result; } catch (err) { - if (err instanceof McpError) throw err; + if (err instanceof McpError) { + // The Go SDK's refusal of a tool it does not serve (rule 4). + if (!listedFromSession && err.code === ErrorCode.InvalidParams && /unknown tool/i.test(err.message)) { + return unknownToolResult(request.params.name); + } + throw err; + } return { isError: true, content: [{ type: "text", text: `Bytebase MCP: ${describe(err)}` }] }; } }); diff --git a/src/tools.ts b/src/tools.ts index 97c856e..36ec5a4 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -5,7 +5,8 @@ import type { Tool } from "@modelcontextprotocol/sdk/types.js"; * The tool definitions shipped with this package, dumped from a Bytebase * release's built-in MCP server by `npm run sync-tools`. They let a directory * (Glama, the MCP Registry, awesome lists) start the server and read its tool - * list without a Bytebase instance; a connected instance's live list wins. + * list without a Bytebase instance, and they are a configured server's list + * until its session answers (docs/DESIGN.md, D2). */ export interface BundledTools { /** Bytebase version the definitions were read from. */ diff --git a/test/config.test.mjs b/test/config.test.mjs index 7877978..b0aec0a 100644 --- a/test/config.test.mjs +++ b/test/config.test.mjs @@ -1,6 +1,22 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { loadConfig, mcpEndpoint, parseBytebaseUrl } from "../dist/config.js"; +import { clientIdentity } from "../dist/auth.js"; + +test("D6: clientIdentity maps Claude Desktop's client names to one sign-in", () => { + const desktop = { key: "claude-ai", clientName: "Claude via Bytebase MCP" }; + assert.deepEqual(clientIdentity({ name: "claude-ai", version: "1" }), desktop, "Chat"); + assert.deepEqual(clientIdentity({ name: "local-agent-mode-Bytebase", version: "1" }), desktop, "Code tab and Cowork"); + assert.deepEqual(clientIdentity({ name: "local-agent-mode-bytebase-dev", version: "1" }), desktop, "any server name"); + assert.deepEqual( + clientIdentity({ name: "Bytebase-era-probe", version: "1" }), + { key: "Bytebase-era-probe", clientName: "Bytebase-era-probe via Bytebase MCP" }, + "the startup probe keeps its own", + ); + assert.deepEqual(clientIdentity({ name: "cursor-vscode", title: "Cursor", version: "1" }), { key: "cursor-vscode", clientName: "Cursor via Bytebase MCP" }); + assert.deepEqual(clientIdentity({ name: "my agent/1", version: "1" }), { key: "my_agent_1", clientName: "my agent/1 via Bytebase MCP" }); + assert.equal(clientIdentity(undefined).key, "unknown-client"); +}); test("parseBytebaseUrl normalizes trailing slash and /mcp", () => { for (const raw of ["https://bb.example.com", "https://bb.example.com/", "https://bb.example.com/mcp", "https://bb.example.com/mcp/", "bb.example.com"]) { diff --git a/test/fake-upstream.mjs b/test/fake-upstream.mjs index f6ad128..280af9a 100644 --- a/test/fake-upstream.mjs +++ b/test/fake-upstream.mjs @@ -142,6 +142,12 @@ export async function startFakeBytebase({ resourceMetadata = true, pageSize = 0, if (message.method === "tools/call") { toolCalls.push(message.params); if (state.callDelayMs > 0) await new Promise((resolve) => setTimeout(resolve, state.callDelayMs)); + // Bytebase's Go SDK refuses a tool it does not serve with this JSON-RPC error (server.go). + const served = [...FAKE_TOOLS.tools.map((tool) => tool.name), ...(reauthorizeTool ? ["reauthorize"] : []), ...(streamed ? ["confirm_change"] : [])]; + if (!served.includes(message.params?.name)) { + json(res, 200, { jsonrpc: "2.0", id: message.id, error: { code: -32602, message: `unknown tool "${message.params?.name}"` } }); + return; + } } if (message.method === "tools/list") { toolLists.push(message.params); diff --git a/test/sessions.test.mjs b/test/sessions.test.mjs index 483dcd5..673841e 100644 --- a/test/sessions.test.mjs +++ b/test/sessions.test.mjs @@ -12,6 +12,8 @@ import { ElicitRequestSchema, ToolListChangedNotificationSchema } from "@modelco import { completeSignIn, startFakeBytebase, SESSION_INSTRUCTIONS } from "./fake-upstream.mjs"; const entry = path.join(import.meta.dirname, "..", "dist", "index.js"); +const snapshot = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "src", "tools.json"), "utf8")); +const snapshotNames = snapshot.tools.map((tool) => tool.name); let nextPort = 52100 + Math.floor(Math.random() * 500); function freshHome() { @@ -74,8 +76,8 @@ test("D5/D6: the first tool call signs in as the real client, then runs", async }); /** Signs one proxy in and closes it, leaving a stored sign-in for the client in `home`. */ -async function signInOnce(bytebase, home, port) { - const proxy = await connect({ url: bytebase.url, home, port }); +async function signInOnce(bytebase, home, port, clientName) { + const proxy = await connect({ url: bytebase.url, home, port, clientName }); const call = proxy.client.callTool({ name: "get_schema", arguments: {} }); await completeSignIn(await proxy.nextSignIn()); await call; @@ -98,6 +100,22 @@ test("S2: a stored sign-in opens the session at initialize and passes its instru assert.equal(proxy.signIns.length, 0); }); +test("D6: Claude Desktop's Code and Cowork process starts with Chat's sign-in and lists tools at once", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port, "claude-ai"); + + const proxy = await connect({ url: bytebase.url, home, port, clientName: "local-agent-mode-Bytebase" }); + t.after(() => proxy.client.close()); + const { tools } = await proxy.client.listTools(); + assert.ok(tools.length > 0, "the first tools/list is not empty, so Desktop keeps the server"); + assert.equal(proxy.signIns.length, 0, "no second sign-in"); + assert.deepEqual(bytebase.registrations.map((r) => r.client_name), ["Claude via Bytebase MCP"]); + assert.equal(bytebase.initializes.at(-1).clientInfo.name, "local-agent-mode-Bytebase", "the real clientInfo still reaches the instance"); +}); + test("D7: two processes refreshing at once send one refresh", async (t) => { const bytebase = await startFakeBytebase(); t.after(() => bytebase.close()); @@ -141,12 +159,12 @@ test("D7: two processes signing in for the first time register once and sign in assert.equal(first.signIns.length + second.signIns.length, 0, "no sign-in URL was printed besides the one used"); }); -test("S3: a configured proxy signs in after initialize and announces its instance's tools", async (t) => { +test("S3: a configured proxy lists the snapshot, signs in after initialize and announces its instance's tools", async (t) => { const bytebase = await startFakeBytebase(); t.after(() => bytebase.close()); const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); t.after(() => proxy.client.close()); - assert.deepEqual((await proxy.client.listTools()).tools, []); + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), snapshotNames); const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); await completeSignIn(await proxy.nextSignIn()); @@ -157,6 +175,42 @@ test("S3: a configured proxy signs in after initialize and announces its instanc ); }); +test("D2: a client that never re-lists signs in on its first call to a snapshot tool, and the call runs", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + // As Claude Desktop's Code and Cowork process: one tools/list, no re-list after tools/list_changed. + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++, clientName: "local-agent-mode-Bytebase" }); + t.after(() => proxy.client.close()); + const listed = (await proxy.client.listTools()).tools.map((tool) => tool.name); + assert.ok(listed.includes("query_database"), "the snapshot names a tool the instance serves"); + + const call = proxy.client.callTool({ name: "query_database", arguments: {} }); + await completeSignIn(await proxy.nextSignIn()); + assert.equal((await call).content[0].text, "ran query_database"); + assert.equal(proxy.signIns.length, 0, "one sign-in"); +}); + +test("rule 4: a snapshot tool the instance does not serve gets an error result naming the snapshot", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); + t.after(() => proxy.client.close()); + const missing = snapshotNames.find((name) => !["query_database", "get_schema"].includes(name)); + assert.ok((await proxy.client.listTools()).tools.some((tool) => tool.name === missing)); + + const call = proxy.client.callTool({ name: missing, arguments: {} }); + await completeSignIn(await proxy.nextSignIn()); + const result = await call; + assert.equal(result.isError, true); + assert.match(result.content[0].text, new RegExp(`no tool named "${missing}"`)); + assert.match(result.content[0].text, new RegExp(`snapshot of Bytebase ${snapshot.bytebaseVersion.replace(/\./g, "\\.")}`)); + assert.match(result.content[0].text, /Reconnect this MCP server/); + + // Once the client holds the instance's own list, the instance's refusal passes through. + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); + await assert.rejects(proxy.client.callTool({ name: missing, arguments: {} }), /unknown tool/); +}); + test("D5: a call cancelled while sign-in is pending is never sent", async (t) => { const bytebase = await startFakeBytebase(); t.after(() => bytebase.close()); @@ -395,7 +449,7 @@ test("D2: tools/list never waits on a sign-in in progress", async (t) => { t.after(() => proxy.client.close()); const started = Date.now(); - assert.deepEqual((await proxy.client.listTools()).tools, [], "no session yet, so nothing to list"); + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), snapshotNames, "no session yet, so the snapshot"); assert.ok(Date.now() - started < 3000, "answered without waiting for the opening"); const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); diff --git a/test/smoke.test.mjs b/test/smoke.test.mjs index 475248b..c999bd7 100644 --- a/test/smoke.test.mjs +++ b/test/smoke.test.mjs @@ -50,7 +50,7 @@ test("S1: with no URL, lists the snapshot, runs nothing, and says no instance is assert.match(result.content[0].text, /BYTEBASE_URL/); }); -test("S3: a configured Bytebase instance without a session lists nothing and says to sign in", async (t) => { +test("S3: a configured Bytebase instance without a session lists the snapshot and says to sign in", async (t) => { const bytebase = await startFakeBytebase(); t.after(() => bytebase.close()); @@ -58,19 +58,25 @@ test("S3: a configured Bytebase instance without a session lists nothing and say t.after(() => formless.close()); const instructions = formless.getInstructions() ?? ""; assert.match(instructions, /sign in/i); + assert.match(instructions, new RegExp(`snapshot of Bytebase ${snapshot.bytebaseVersion.replace(/\./g, "\\.")}`), "says the list is the snapshot"); assert.match(instructions, /confirmation form/, "a client without forms gets the package's form sentence"); - assert.deepEqual((await formless.listTools()).tools, [], "a configured proxy never lists the snapshot"); + assert.deepEqual( + (await formless.listTools()).tools.map((tool) => tool.name), + snapshot.tools.map((tool) => tool.name), + "never an empty first list, which Claude Desktop's Code and Cowork process drops", + ); const withForm = await connect({ BYTEBASE_URL: bytebase.url }, { form: true }); t.after(() => withForm.close()); assert.ok(!(withForm.getInstructions() ?? "").includes("confirmation form")); }); -test("S4: an unreachable instance and a server that is not Bytebase each say so and list nothing", async (t) => { +test("S4: an unreachable instance and a server that is not Bytebase each say so and list the snapshot", async (t) => { + const snapshotNames = snapshot.tools.map((tool) => tool.name); const unreachable = await connect({ BYTEBASE_URL: "http://127.0.0.1:9" }); t.after(() => unreachable.close()); assert.match(unreachable.getInstructions() ?? "", /could not be reached/); - assert.deepEqual((await unreachable.listTools()).tools, []); + assert.deepEqual((await unreachable.listTools()).tools.map((tool) => tool.name), snapshotNames); const other = await startFakeBytebase({ resourceMetadata: false }); t.after(() => other.close()); @@ -79,5 +85,5 @@ test("S4: an unreachable instance and a server that is not Bytebase each say so const instructions = notBytebase.getInstructions() ?? ""; assert.match(instructions, /does not answer as a Bytebase instance/); assert.match(instructions, /external URL/); - assert.deepEqual((await notBytebase.listTools()).tools, []); + assert.deepEqual((await notBytebase.listTools()).tools.map((tool) => tool.name), snapshotNames); });