diff --git a/.gitignore b/.gitignore index 50fdb18..756ca9e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ dist/ .env *.tgz test/.tmp-home/ +test/.tmp-home-*/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ff02b54 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,169 @@ +# Contributing + +The design, with every state the server can be in, is in [docs/DESIGN.md](docs/DESIGN.md). This +file covers building, testing and releasing. + +## Build and test + +Node.js 20 or later. + +```bash +npm install +npm run build +npm test +``` + +`npm test` drives the built server over stdio against a fake Bytebase (`test/fake-upstream.mjs`): +an OAuth server with PKCE and single-use refresh tokens, and an MCP endpoint. No instance or +browser is needed. It takes about two minutes; one test keeps a confirmation form open for longer +than a minute on purpose. + +## Testing at four levels + +Each level catches what the one before cannot. + +1. **`npm test`**: every state, sign-in, the token lock, paging and recovery, against the fake. +2. **The directory view**: what an MCP directory sees with no instance configured. Open it in the + MCP Inspector: + + ```bash + npx @modelcontextprotocol/inspector node dist/index.js + ``` + + Or print the tool list without the UI: + + ```bash + npx @modelcontextprotocol/inspector --cli node dist/index.js --method tools/list + ``` + + 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. + + ```bash + BYTEBASE_URL=http://localhost:8080 BYTEBASE_MCP_HOME="$(mktemp -d)" node scripts/check-live.mjs + ``` + +4. **A real client**, from a packed tarball, as users will run it (below). + +## A Bytebase to sign in to + +Sign-in goes through the instance's consent page: the authorize endpoint redirects the browser to +`/oauth2/consent` on the same host and port. So the instance must serve its console and its API +together: + +- A backend built without the frontend answers that page with "This Bytebase build does not bundle + frontend and backend together", so sign-in cannot finish. +- The frontend dev server does not forward `/mcp`, so a frontend dev server in front of a separate + backend cannot complete sign-in either. + +Build a bundled binary in the [bytebase](https://github.com/bytebase/bytebase) repository, as its +end-to-end tests do (`frontend/tests/e2e/README.md`), then run it with its external URL set, since +Bytebase binds MCP tokens to it: + +```bash +(cd frontend && pnpm release) +bash frontend/tests/e2e/build-server.sh # writes ./bytebase-build/bytebase +./bytebase-build/bytebase --port 8080 --external-url http://localhost:8080 --data "$(mktemp -d)" +``` + +Without `PG_URL` it starts on embedded PostgreSQL. Sign up the first account in the browser at +`http://localhost:8080`. + +## Testing a packed tarball in a client + +```bash +npm run build +npm pack # writes bytebase-bytebase-mcp-.tgz +``` + +Point the client at the tarball with `--package` and an absolute path: + +```json +{ + "mcpServers": { + "bytebase-local": { + "command": "npx", + "args": ["-y", "--package=/absolute/path/to/bytebase-bytebase-mcp-0.1.0.tgz", "bytebase-mcp"], + "env": { + "BYTEBASE_URL": "http://localhost:8080", + "BYTEBASE_MCP_HOME": "/tmp/bytebase-mcp-test" + } + } + } +} +``` + +In Claude Code: + +```bash +claude mcp add bytebase-local -e BYTEBASE_URL=http://localhost:8080 -e BYTEBASE_MCP_HOME=/tmp/bytebase-mcp-test -- npx -y --package=/absolute/path/to/bytebase-bytebase-mcp-0.1.0.tgz bytebase-mcp +``` + +Two forms that look equivalent are not: + +- `npx -y /absolute/path/to/x.tgz` fails with "Permission denied", and the client reports the + connection closed. npx looks for a local program by joining its argument onto + `node_modules/.bin`; an absolute path survives the join, the tarball exists, so npx tries to + execute the tarball itself. +- `npx -y ./x.tgz` works, but only when started from that folder, and a client does not start + there. + +After re-packing, npx installs the new tarball even at the same path (checked with npm 11.6.1). +Its installs stay in the npx cache; find and remove them with: + +```bash +grep -l bytebase-mcp ~/.npm/_npx/*/package.json # remove each listed file's directory +``` + +## Keeping test sign-ins apart + +Sign-ins live in `~/.bytebase-mcp` by default. Set `BYTEBASE_MCP_HOME` to a throwaway directory +while testing, so your own sign-ins are untouched. To see and clear them: + +```bash +BYTEBASE_MCP_HOME=/tmp/bytebase-mcp-test node dist/index.js status --url http://localhost:8080 +BYTEBASE_MCP_HOME=/tmp/bytebase-mcp-test node dist/index.js logout --url http://localhost:8080 +``` + +`logout` revokes each refresh token at the instance, then deletes it. + +## Manual checks before a release + +The automated tests do not cover these: + +- [ ] The browser consent page names the client (` via Bytebase MCP`), and allowing it + finishes the sign-in. +- [ ] On a first run, the tools appear after sign-in without restarting the client (the client + 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. + +## 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: + +```bash +npm run build +BYTEBASE_URL=https://your-bytebase npm run sync-tools +``` + +The script signs in like the package does, writes the snapshot and the README's tools table, and +prints what changed. + +## Releasing + +```bash +npm version patch # bumps package.json and server.json together +git push origin main --follow-tags +``` + +A push to `main` that changes `package.json` runs +[`npm-publish.yml`](.github/workflows/npm-publish.yml): it publishes to npm with OIDC provenance, +then registers the version in the [MCP Registry](https://registry.modelcontextprotocol.io) with +`mcp-publisher`. No tokens are stored in the repository. diff --git a/README.md b/README.md index c615e2f..347b30c 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,20 @@ [![npm](https://img.shields.io/npm/v/@bytebase/bytebase-mcp)](https://www.npmjs.com/package/@bytebase/bytebase-mcp) -The official npm package for the [Bytebase](https://www.bytebase.com) MCP server. It lets AI assistants that run MCP servers as local commands (Claude Desktop, Cursor, Windsurf, and others) use the MCP server built into your Bytebase instance: query data, inspect schemas, and propose database changes, all under Bytebase's approvals, access control, data masking, and audit logging. +The official npm package for the [Bytebase](https://www.bytebase.com) MCP server. It lets AI assistants that can only run MCP servers as local commands use the MCP server built into your Bytebase instance: query data, inspect schemas, and propose database changes, all under Bytebase's approvals, access control, data masking, and audit logging. ``` AI assistant --stdio--> bytebase-mcp --HTTPS + OAuth--> /mcp --> your databases ``` -The package contains no database logic of its own. It ships the tool definitions of Bytebase's built-in MCP server and forwards every call to your instance, where permissions, the workspace MCP access policy, approvals and audit apply exactly as in the console. Nothing is cached or executed locally except the OAuth token. +The package contains no Bytebase logic. Once you sign in, it lists your instance's own tools and forwards every call to the instance, where permissions, the workspace MCP access policy, approvals and audit apply exactly as in the console. Nothing is stored locally except the OAuth token. -> If your client supports remote MCP servers over HTTP (Claude Code, Codex, Copilot CLI, Gemini CLI, VS Code, Claude Desktop connectors), you do not need this package: point the client straight at `/mcp`. See the [MCP integration docs](https://docs.bytebase.com/integrations/mcp). +> Most clients, including Claude Code, Claude Desktop, Cursor, Codex, Copilot CLI, Gemini CLI and VS Code, connect to remote MCP servers over HTTP. They do not need this package: point them straight at `/mcp`. See the [MCP integration docs](https://docs.bytebase.com/integrations/mcp). This package is for clients that only start local commands, and for MCP directories. ## Requirements - A Bytebase instance, 3.22 or later, with its [external URL](https://docs.bytebase.com/get-started/self-host/external-url) configured and the workspace MCP access policy not set to **Disabled**. -- Node.js 20 or later. +- Node.js 20 or later, on macOS or Linux. Windows has not been tested yet. If your browser does not open at sign-in there, find the sign-in URL in the server's output (your client's MCP log) and open it yourself. - A Bytebase account. The package signs you in through Bytebase's own OAuth; it never sees your password. ## Setup @@ -36,23 +36,15 @@ Add the server to your MCP client with your instance's external URL: } ``` -The first tool call opens your browser on Bytebase's authorization page. Sign in, review what the session may do, and click **Allow**. The token is stored under `~/.config/bytebase-mcp/` with owner-only permissions and refreshed automatically. - -To sign in ahead of time, or on a machine without a browser: - -```bash -BYTEBASE_URL=https://bytebase.example.com npx -y @bytebase/bytebase-mcp login -BYTEBASE_MCP_NO_BROWSER=1 BYTEBASE_URL=https://bytebase.example.com npx -y @bytebase/bytebase-mcp login # prints the URL instead -``` +When the server first starts, it opens your browser on Bytebase's authorization page. Sign in, review what the session may do, and click **Allow**. Bytebase shows your AI client by name there, and each client application signs in once per instance. The token is stored under `~/.bytebase-mcp/` with owner-only permissions and refreshed automatically; several sessions share it safely. Set `BYTEBASE_MCP_NO_BROWSER=1` to print the sign-in URL instead of opening a browser. ### Commands | Command | What it does | | --- | --- | | `bytebase-mcp` | Serve MCP over stdio (what your client runs) | -| `bytebase-mcp login` | Sign in now and store the token | -| `bytebase-mcp logout` | Forget the stored sign-in | -| `bytebase-mcp whoami` | Show the instance, token file, and the live tool list | +| `bytebase-mcp status` | Show the instance and the stored sign-ins, without signing in | +| `bytebase-mcp logout` | Revoke and forget every sign-in stored for the instance (does not sign you out of the console). To switch accounts: log out, reconnect the server in your client, sign in as the other account | Every command takes `--url ` in place of `BYTEBASE_URL`. @@ -61,71 +53,46 @@ Every command takes `--url ` in place of `BYTEBASE_URL`. | Variable | Default | Purpose | | --- | --- | --- | | `BYTEBASE_URL` | – | External URL of the instance. Required to call tools. | -| `BYTEBASE_MCP_HOME` | `~/.config/bytebase-mcp` | Where token files live, one per instance host | +| `BYTEBASE_MCP_HOME` | `~/.bytebase-mcp` | Where sign-ins live, one per instance and client app | | `BYTEBASE_MCP_CALLBACK_PORT` | `51789` | Loopback port that receives the OAuth redirect | | `BYTEBASE_MCP_NO_BROWSER` | unset | Set to `1` to print the sign-in URL instead of opening a browser | ## Tools -The tools are Bytebase's. The list below is generated from the release named in `src/tools.json`; a connected instance's live list replaces it, so an older or newer Bytebase shows its own 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: -Generated from Bytebase 3.24.1. +Generated from Bytebase 3.25.0. | Tool | Purpose | | --- | --- | +| `administer_workspace` | Make a workspace administration change that the user confirms in this client first. | | `call_api` | Execute a Bytebase API endpoint. | | `decide_issue` | Approve or reject a Bytebase issue at its current approval step. | +| `get_gitops_workflow` | Return the workflow files that set up GitOps for a project. | | `get_schema` | Inspect a Bytebase database's schema. | -| `get_skill` | Get step-by-step guides for Bytebase tasks. | -| `grant_masking_exemption` | Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table or column) or for every database in the project. | +| `grant_masking_exemption` | Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table, or columns of one table) or for every database in the project. | | `propose_database_change` | Run DDL/DML changes (ALTER TABLE, CREATE TABLE, INSERT, UPDATE, migrations) against a Bytebase database. | | `query_database` | Execute a SQL query against a Bytebase database. | | `reauthorize` | Log out the current MCP OAuth connection so the client can run OAuth again. | +| `request_access_grant` | Request an access grant: time-boxed permission to run one read-only statement on one Bytebase database, optionally with results unmasked or exported. | | `revoke_masking_exemption` | Remove one member's masking exemption in a Bytebase project. | | `search_api` | Discover Bytebase API endpoints. | | `set_just_in_time_access` | Turn just-in-time access on or off for one Bytebase project. | -What each session may do is set on the instance: the signed-in user's permissions, narrowed by the workspace [MCP access policy](https://docs.bytebase.com/integrations/mcp#access-policy) (Disabled, Read-only, Read-write). Actions that need confirmation (approving an issue, granting a masking exemption) show a confirmation form in clients that support MCP elicitation; the package forwards the form to your client. - ## How it works -1. On start, the server answers `initialize` and `tools/list` from the bundled definitions, so your client has the tool list at once, and so MCP directories can read it without an instance. -2. On the first `tools/call` (or in the background after `tools/list` when `BYTEBASE_URL` is set), it connects to `/mcp` over Streamable HTTP. If there is 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 calls, results and elicitation requests pass through unchanged. If the live tool list differs from the bundle, the server sends `tools/list_changed`. +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. +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. -Bytebase's refresh tokens are single-use and MCP clients start one process per session, so the token file is re-read before each refresh and written atomically. +The design, with every state the server can be in, is in [docs/DESIGN.md](docs/DESIGN.md). ## Development -Design notes for reviewers and maintainers: [docs/DESIGN.md](docs/DESIGN.md). - -```bash -npm install -npm run build -npm test # unit + cold-start smoke tests, no instance needed -``` - -### Keeping the tool definitions in sync - -`src/tools.json` is generated, never edited. Before each release, dump the tool list from an instance running the Bytebase version you want to ship with: - -```bash -npm run build -BYTEBASE_URL=https://your-bytebase npm run sync-tools -``` - -The script signs in like the package does and prints what changed. Commit the result with the version bump. - -### Releasing - -```bash -npm version patch # bumps package.json and server.json together -git push origin main --follow-tags -``` - -A push to `main` that changes `package.json` runs [`npm-publish.yml`](.github/workflows/npm-publish.yml): it publishes to npm with OIDC provenance, then registers the version in the [MCP Registry](https://registry.modelcontextprotocol.io) with `mcp-publisher`. No tokens are stored in the repository. +Building, testing (against a local Bytebase and in a real client), keeping the tool snapshot current and releasing are covered in [CONTRIBUTING.md](CONTRIBUTING.md). The design is in [docs/DESIGN.md](docs/DESIGN.md). ## License diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 25c5567..73874dc 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,145 +1,335 @@ -# Design notes +# Design: a proxy that gets Bytebase's tools from the instance -Context for reviewers and maintainers. Written 2026-11-16 by Adela (with Claude) when the -package was first built, so nobody has to redo the research. Linear: BYT-10055. +Status: proposal (revision 2) · 2026-11-22 · Linear BYT-10055 -## 1. Problem +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 ships an MCP server inside the product at `/mcp` (Streamable HTTP, -OAuth-protected; code in `backend/api/mcp/`). It works, but it cannot be listed in any MCP +## Problem + +Bytebase serves MCP at `/mcp` (Streamable HTTP, OAuth). It is not in any MCP directory: -- Directories (Glama, the official MCP Registry, awesome-mcp-servers) list servers they can - **start themselves** and read `tools/list` from, **without signing in**. The built-in server - only runs inside the Bytebase process and refuses everything before OAuth. -- Result: Bytebase is absent from every directory. AI-visibility data (W43) ranks us 3rd on - the MCP topic, but none of the top-6 cited sources is ours; all six are standalone server - repos. -- A third party filled the gap: `ahmedbally/bytebase-mcp` holds the npm name `bytebase-mcp` - and ranks first for "bytebase" on Glama. It reimplements 14 tools of its own on top of the - Connect-RPC API, does its own read/write gating, and has not been maintained since - 2026-09-14. - -## 2. What this package is - -A stdio MCP server (what every directory and local-only client can start) that does two -things and nothing else: - -1. **Ships the built-in server's tool definitions** (`src/tools.json`) so `initialize` and - `tools/list` work with no instance. This is what makes the directory cold start pass. -2. **Forwards `tools/call` and elicitation to `/mcp`**, signing in with the - instance's own OAuth. Results pass through untouched. Permissions, the workspace MCP - access policy, approvals, masking and audit stay on the instance. - -It deliberately contains **no tool logic of its own**. The third-party package is a parallel -implementation that drifts from the product; this one cannot drift because it has nothing to -drift. - -``` -AI client --stdio--> bytebase-mcp --Streamable HTTP + OAuth--> /mcp --> databases -``` - -Users whose client speaks remote MCP (Claude Code, Codex, Copilot CLI, Gemini CLI, VS Code, -Claude Desktop connectors) do not need this package and should keep pointing at `/mcp` -directly. The package is for (a) directories and (b) clients that only start local commands -(Cursor, Windsurf, older clients). - -## 3. How the pieces fit - -| File | Role | -| --- | --- | -| `src/index.ts` | CLI: `serve` (default), `login`, `logout`, `whoami`, `--url` | -| `src/server.ts` | Downstream stdio `Server`. Answers `tools/list` from the bundle at once, never blocking on sign-in; kicks off a background live fetch and sends `tools/list_changed` if the live list differs. `tools/call` goes to the upstream. Elicitation requests from Bytebase are forwarded with `server.elicitInput`. | -| `src/upstream.ts` | One lazy `Client` to `/mcp` over `StreamableHTTPClientTransport` with an `authProvider`. Reconnects once on connection loss. Declares `elicitation` to Bytebase only if the downstream client declared it to us. | -| `src/auth.ts` | `OAuthClientProvider` backed by one 0600 JSON file per instance host under `~/.config/bytebase-mcp/`. The SDK does discovery (`/.well-known/oauth-protected-resource/mcp`), dynamic client registration, PKCE, token exchange and refresh. This file adds the browser leg: loopback listener on `127.0.0.1:51789/callback`, opens the browser, verifies `state`. | -| `src/tools.json` | Generated. `bytebaseVersion`, `instructions`, `tools[]` as served by that release. | -| `scripts/sync-tools.mjs` | Connects like the package does, dumps `tools/list` + initialize instructions, strips the per-session account line, rewrites `src/tools.json` and the README tools table, prints the diff. | -| `scripts/check-live.mjs` | Manual end-to-end: start `dist/index.js` as a client would, call `search_api` and `call_api` through it. | -| `server.json`, `glama.json`, `.github/workflows/npm-publish.yml` | Copied from `bytebase/dbhub`: MCP Registry metadata, Glama maintainer claim, npm OIDC publish → `mcp-publisher publish`. | - -Dependency: `@modelcontextprotocol/sdk` 1.x only (1.32.2 at time of writing). It negotiates -protocol 2025-11-25, which is also the ceiling the Go server answers with -(`legacyProtocolCeiling`), so the newer 2026-07-28 `InputRequests`/`RequestState` multi -round-trip shape never comes up; confirmations arrive as in-call `elicitation/create` requests -and are forwarded as such. - -## 4. Decisions and why - -- **Why ship tool definitions instead of a pure proxy.** Glama starts the server with no - instance. A pure proxy would answer `tools/list` with a connection error and fail the scan. - (Adela's Nov 6 note on BYT-10055.) -- **Why `tools/list` never waits for sign-in.** Claude Code and others call `tools/list` at - startup. Blocking it on a browser round trip would stall the client for minutes on first - run. So: answer from the bundle, fetch live in the background, announce `list_changed`. -- **Why the live list wins when connected.** A user on 3.22 or 3.26 should see their - instance's tools, not the bundle's. The bundle is only the no-instance fallback. -- **Why OAuth and not a service-account token.** The `/mcp` route accepts only its own OAuth - tokens (bound to the external URL); API tokens are refused there. Also keeps the package - free of any Bytebase credential handling. -- **Why a fixed loopback port (51789).** Dynamic client registration stores the redirect URI - with the client; a random port would break every later sign-in. Overridable via - `BYTEBASE_MCP_CALLBACK_PORT`, with a hint to clear the token dir if changed. -- **Why re-read the token file before every refresh.** Bytebase refresh tokens are single-use - and MCP clients start one process per session; a sibling process may have rotated the - token. Writes are atomic (tmp + rename). There is **no cross-process lock** yet; see §7. -- **Why `client.request` instead of `client.callTool`.** `callTool` validates - `structuredContent` against a tool list it may not have fetched. Raw request = pass-through. -- **Fallback instructions.** 3.24.1 sends no initialize `instructions` (the server-side text - landed on main later). The package carries a short routing paragraph used only when the - bundle's `instructions` is empty. -- **License MIT**, matching DBHub. Flagged, not confirmed by anyone else. - -## 5. What was verified (2026-11-13, local Bytebase 3.24.1 via its ngrok external URL) - -- Unit tests + cold-start smoke tests pass (`npm test`), Node 20 and 22 in CI. -- Cold start with no `BYTEBASE_URL`: initialize + `tools/list` return the 11 bundled tools; - `tools/call` returns `isError` with a clear "set BYTEBASE_URL" message. -- Unreachable instance: bundle still served, call errors are readable. -- Live: OAuth flow end to end (registration, browser, callback, token stored), then - `search_api(service="ProjectService")` and `call_api(ProjectService/ListProjects)` through - the stdio server returned 200 from the instance. Live `tools/list` matched the bundle. -- `npm pack` → install in an empty project → `npx bytebase-mcp` cold start lists 11 tools. - Tarball is 20 KB. - -## 6. What was NOT verified - -- **Elicitation forwarding** (confirmation forms for `decide_issue`, masking exemptions, - `set_just_in_time_access`). Implemented, not exercised: needs a Read-write policy and a - client with form elicitation. Worth one manual run from Claude Code before 1.0. -- Token refresh after expiry, and the two-process refresh race. -- Windows (`cmd /c start` for the browser is untested). - -## 7. Known gaps / asks - -1. **Tool-definition sync depends on a running instance and a browser login.** A - `bytebase` CLI subcommand (or `go run`) that dumps the registered MCP tools as JSON would - let CI regenerate `tools.json` on every release with no human. Suggested home: the - bytebase repo, next to `backend/api/mcp/server.go` (`registerTools`). -2. **No cross-process refresh lock.** The third-party package uses an atomic `mkdir` lock - and re-reads after acquiring it. If users report `invalid_grant` with several clients - open, add the same. -3. **Bundle is behind main.** 3.24.1 has 11 tools; main also registers - `request_access_grant` and `administer_workspace`. Re-run `sync-tools` on the next release. -4. **npm trusted publisher not configured.** The publish workflow stops at `ENEEDAUTH` until - `@bytebase/bytebase-mcp` has a trusted publisher (org `bytebase`, repo `bytebase-mcp`, - workflow `npm-publish.yml`). Needs an npm org owner. Registry side needs nothing: - `mcp-publisher login github-oidc` proves `io.github.bytebase/*` through the repo. - -## 8. Release checklist - -1. `npm run build && BYTEBASE_URL= npm run sync-tools` -2. Review the printed added/removed/changed tools; commit `src/tools.json` + README. -3. `npm version ` (also stamps `server.json`), push `main` with tags. -4. The push runs `npm-publish.yml`: npm publish with provenance → wait for npm → - `mcp-publisher publish`. Re-running the job is safe; both steps skip what already exists. -5. After the first publish: claim on Glama (`glama.json` names `adela-bytebase`), open the - awesome-mcp-servers PR, update the MCP directory tracker sheet. - -## 9. References - -- Linear BYT-10055 (problem statement, Nov 6 update on directory constraints) -- `bytebase/dbhub`: `server.json`, `glama.json`, `.github/workflows/npm-publish.yml` (templates) -- `bytebase/bytebase` `backend/api/mcp/`: `server.go` (protocol ceiling, instructions, - `registerTools`), `tool_confirm.go` (elicitation shape), `tool_call.go` -- docs: https://docs.bytebase.com/integrations/mcp -- Third-party package: https://github.com/ahmedbally/bytebase-mcp +- Of the directories that matter, only Glama starts a package to read its tools. It builds the + repository and starts the server with no configuration, then reads `tools/list`. The official + MCP registry and awesome-mcp-servers list a package from its metadata and never start it. +- The built-in server runs only inside the Bytebase process, and `/mcp` answers every request + without a valid bearer token with 401 (`authMiddleware` in `backend/api/mcp/server.go`). +- A third-party package holds the npm name `bytebase-mcp` and ranks first for "bytebase" on Glama. + It reimplements its own tools on the Connect API and has not been maintained since 2026-09-14 + (Adela's notes, 2026-11-16). + +The first version shipped `src/tools.json`, dumped from Bytebase 3.24.1, and answered every +client's `tools/list` from it until a live list arrived. Within a week it was stale: main dropped +`get_skill` and added `request_access_grant`, `administer_workspace` and `get_gitops_workflow`. +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). + +## Approaches weighed + +**A. One bundled list for everyone (first version).** Works offline, but every user sees a list +frozen at the last sync. Rejected for drift. + +**B. Source in a subfolder of the main repository, with a mirror for directories.** A Go test +writes the list at each release. That narrows the drift without removing it (Cloud deploys between +releases; older instances get a newer list), and adds mirror machinery. Rejected. + +**C. A public catalog route on the server.** `GET /mcp/catalog` answering without a token, read by +the package before sign-in. Built and reviewed in bytebase/bytebase#22184, then closed: its only +consumer is a directory scan of an unconfigured package, which does not justify an unauthenticated +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. + +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 +`initialize` runs into client startup timeouts; that fork's README lists Claude's 60-second timeout +as an open problem. So this proxy answers `initialize` at once and signs in afterwards (D4, D5). + +The package stays in its own repository, for the reasons the first version gave: Glama and the +awesome list index a repository root, the license is plain MIT, npm trusted publishing and the +registry's OIDC bind to one repository and workflow, and releases are independent (precedent: +`bytebase/dbhub`). + +## Decisions + +**D1 · The instance is named by `BYTEBASE_URL` or `--url`.** `--url` wins when both are set. The +value is the instance's external URL; `parseBytebaseUrl` accepts a bare host and strips a trailing +`/` or `/mcp`. This follows comparable packages (`GRAFANA_URL`, `JIRA_URL`, `mcp-remote `). +Configuration is read once, at startup: a changed URL takes effect when the client restarts the +server, with a fresh `initialize`, so one process never changes state between unconfigured and +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.** + +- 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.** +`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. + +**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` +(States below): + +- No URL (S1): a one-line note that no instance is connected, then the snapshot's instructions. +- Signed in (S2): the instance's own initialize instructions, verbatim. The proxy opens the session + inside the client's `initialize`, declaring elicitation exactly as the client declared it, so + 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 + `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 + (`declaresFormElicitation` in Bytebase's `tool_resolve.go`). + +Opening the session and probing the instance are bounded at 5 seconds in total, so a client's +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 +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. + +A forwarded request belongs to whoever sent it: **the proxy adds no deadline and no cancellation +of its own, in either direction, and passes the sender's cancellation on.** The SDK gives every +request a 60-second default, so each forwarded request sets its own. Every request the proxy +forwards: + +| Request | Direction | Proxy's timeout | Cancellation | +| --- | --- | --- | --- | +| `tools/call` | client → Bytebase | None | The client's is passed to Bytebase; a call cancelled before its session opens is never sent | +| `tools/list` | client → Bytebase | 10 seconds while reopening a session (D2's one exception), then a JSON-RPC error | The client's, and the bound's, abort it before it is sent | +| `elicitation/create` (a confirmation form) | Bytebase → client | None; Bytebase decides how long a form stays up (10 minutes, `confirmationLifetime` in `tool_confirm.go`) | Bytebase's is passed to the client, which takes the form down | +| `tools/list_changed` | Bytebase → client | — (a notification) | — | + +Bytebase sends no other request or notification during a call, so the table is complete; a new one +is added here before it is forwarded. Any forwarded request, `tools/list` as well as `tools/call`, +is resent only after an error showing the instance never received it (connection refused, 401, +unknown session), on a session reopened with the stored sign-in; Bytebase ends a session after an +hour idle. Reopening never cuts off calls already in flight on the old session: they may have run, +so they finish and return their results, and the old session closes after them. The SDK drives OAuth: +protected-resource discovery, dynamic client registration, PKCE, token exchange. The package +handles the browser leg on the fixed loopback port 51789 (`BYTEBASE_MCP_CALLBACK_PORT`), and +prints the sign-in URL only once that port is listening. The URL comes from the instance's OAuth +metadata, so the proxy opens it in a browser only if it is http(s), and never through a shell (on +Windows, `rundll32 url.dll,FileProtocolHandler`, since `cmd` would run what a URL's `|` or `^` +introduces); otherwise the printed URL is all there is. + +**D6 · The real client's identity reaches the instance.** A sign-in belongs to one client +application on one instance. The proxy registers one OAuth client per `(instance, client)`, named +` via Bytebase MCP`. It forwards the client's `clientInfo` +unchanged in its own `initialize` to the instance. The instance shows the registration's +`client_name` on the consent page (`handleGetClient`, `backend/api/oauth2/oauth2.go`) and records +the OAuth client ID in the MCP delegation of its audit rows (`backend/api/v1/audit.go`, +`backend/api/mcp/connection_audit.go`). So each client application gets its own consent and its +own client ID in audit; the audit table shows that ID, not the name (Not in this change). The +first version registered every session as one "Bytebase MCP (npm)" client. Consequence: each +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. + +**D7 · Tokens are stored per sign-in, and one lock guards every write.** One file per sign-in at +`//.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 +`backend/api/oauth2/token.go`), and clients start one proxy process per session, so several +processes share one sign-in. Rules: + +- **The sign-in file is written only while holding its lock**: a directory `.lock`, created + by renaming one that already holds the owner's process ID, abandoned once that process is gone. +- Signing in (registration through saved tokens) and refreshing (token request through saved + tokens) each run under the lock. A process that gets the lock re-reads the file and skips what + it shows done: it reuses a stored registration, and uses tokens newer than its own instead of + refreshing. +- The PKCE verifier and `state` stay in the memory of the process that started the sign-in. +- A process deletes tokens or a registration the instance refused only if the file still holds + what it sent. +- The browser leg also holds a machine-wide lock on the callback port, which every sign-in on the + machine shares. +- Nothing waits for a lock inside `initialize`. There the proxy uses what the file holds, and a + sign-in it would need makes the state signed out (S3). + +The SDK ends a sign-in at the browser redirect and exchanges the code in a later call, and saves +tokens only after a token request returns. So the proxy takes the lock itself, at two places: + +- Around opening a session: from before the SDK reads the stored registration until the session + is open or has failed. This spans registration, the browser leg and the code exchange. +- Around a refresh in an open session: in the `fetch` the proxy gives the SDK transport, from the + token request until the result is on disk. The SDK builds the request from tokens it read + earlier, so when the file holds newer tokens than the rejected ones, the `fetch` answers with + those instead of sending the request. + +The lock is reentrant only while the session opening that holds it is in progress, so a refresh +inside that opening does not wait on itself, and work the opening starts but outlives it (the SDK's +event stream) takes the lock like anyone else. Concurrent refreshes in one process wait for each +other as those of different processes do. A sign-in starts only while a session is being opened +for D5's sign-in or a tool call. If the SDK tries to start one anywhere else, as it does after a +refused refresh (a revoked grant, as after Bytebase's `reauthorize`), the provider refuses it; the +instance answered 401, so the request never ran, and a tool call reopens the session with a sign-in +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 +following `package.json` (`scripts/sync-version.mjs`). + +**D9 · The commands are `serve`, `logout` and `status`.** `serve` (the default) is what clients +run. `logout` revokes each refresh token stored for the instance at its revocation endpoint, so a +copied file stops working too, then deletes the sign-in under its own lock; it is also how a user +switches accounts (log out, reconnect, sign in as the other account). It does not sign anyone out +of the Bytebase console. `status` prints the instance, whether +it answers as Bytebase, and the stored sign-ins by client, without signing in. `login` goes (D6); `whoami` becomes `status`, which needs no session. + +## States + +A configured proxy decides its state at startup from two facts: whether a stored sign-in opens a +session within the initialize bound without asking the user, and what +`GET /.well-known/oauth-protected-resource/mcp` returns. A JSON document whose `resource` is +`/mcp` means Bytebase. No answer within the bound, or HTTP 502, 503 or 504 (a gateway +answering for a Bytebase that is down or restarting), means unreachable, here and in D5's retry. +Any other answer means not Bytebase. + +| State | Instructions at initialize | `tools/list` | `tools/call` | +| --- | --- | --- | --- | +| **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. | + +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. +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 + 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). +5. Elicitation is declared to the instance only if the client declared it; requests are forwarded + with `server.elicitInput`. +6. Diagnostics go to stderr; stdout is the transport. + +If sign-in fails because the instance's protected-resource document names another URL, the error +says that `BYTEBASE_URL` must be the instance's external URL, which is what tokens are bound to. + +## Scope + +This pull request first carried revision 1 (a public catalog route): its design commit, a slice +that read the catalog, and a slice that built sessions, sign-in, the token lock, identity, +cancellation and the `status` and `logout` commands. That session code already does most of what +D5–D7 and D9 describe, and its tests (`test/sessions.test.mjs`) stay green throughout. Revision 2 +lands as two more commit series on top, each green on its own, so `npm test` passes after each. +Tests drive the built server over stdio against a fake Bytebase: a local HTTP server with the +protected-resource document, an OAuth server and an MCP endpoint built with the SDK's server. + +1. **States and the snapshot.** Delivers D1–D4, D8, the states' instructions and lists (S1, S3, + S4; S2 keeps the existing session code), D5's sign-in after `initialized` for every configured + proxy without a session, rules 1–2, and the README. Removes `src/catalog.ts` and the catalog + paths in `src/server.ts` and `src/index.ts` (`status` stops reporting a catalog). Restores + `src/tools.ts`, `scripts/sync-tools.mjs` and `scripts/render-readme.mjs`, adds the build step + that copies the snapshot into `dist/`, and seeds `src/tools.json` from the latest Bytebase + release with `sync-tools`, so S1 carries current instructions. Tests: `test/smoke.test.mjs` by state, + and the existing `test/sessions.test.mjs` updated where a state's name or `status`'s output + changed. +2. **Pages and recovery.** Delivers the rest of D2 and D5 and rule 3: cursors passed through to the + session, every reader taking every page (`sync-tools` and the proxy's own reads), opening + retries with backoff when the instance cannot be reached, resending `tools/list` on a reopened + session, and the JSON-RPC error for a `tools/list` that cannot be answered. Files: + `src/upstream.ts`, `src/server.ts`, `scripts/sync-tools.mjs`, and `test/sessions.test.mjs` + (paging through a fake that pages, an expired session, an unreachable first start). Depends on + slice 1. + +## Not in this change + +- 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. +- 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. + Both are work in the main repository. +- Windows has never been run, so the README says so; a manual run comes before 1.0. + +## 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. +- 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 + client. +- `client.request` rather than `client.callTool`, which would validate `structuredContent` against + a tool list it may not have fetched. +- Atomic token writes, and re-reading the file before use. +- `@modelcontextprotocol/sdk` 1.x, which negotiates protocol 2025-11-25, the ceiling the Go server + answers with (`legacyProtocolCeiling`). Confirmations stay in-call `elicitation/create` + requests. +- `server.json`, `glama.json` and the publish workflow from `bytebase/dbhub`. The npm trusted + publisher still needs an npm org owner. + +## What changed + +| 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) | +| 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 | +| One OAuth client, "Bytebase MCP (npm)" | One per (instance, client app) | Consent and audit show the real client (D6) | +| Token file per host, no lock | Per (instance, client); every write under one lock | Single-use refresh tokens, several processes (D7) | +| Cancelled calls forwarded; replays on ambiguous errors | Never sent once cancelled; resent only when never received | D5 | +| `login`, `whoami` | `status` | A sign-in needs a client (D6, D9) | +| README calls Cursor and Claude Desktop local-command-only | Both connect to remote `/mcp`; the package is for directories and local-command clients | Correctness | + +## References + +- bytebase `backend/api/mcp/server.go`: `authMiddleware`, `registerTools`, `askInChatWithoutForm`, + `nameSignedInAccount`, `legacyProtocolCeiling`. +- bytebase/bytebase#22184 (closed): the public catalog route of approach C. +- `mcp-remote` (geelen/mcp-remote) `src/proxy.ts`: sign in, then connect and pass through. +- Glama listings of sign-in-first bridges (`abluva/mcp-remote` and others): listed, "Not graded" + quality, no tools. diff --git a/package-lock.json b/package-lock.json index 5f64305..60ca652 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "0.1.0", "license": "MIT", "dependencies": { - "@modelcontextprotocol/sdk": "^1.32.2" + "@modelcontextprotocol/sdk": "1.32.2" }, "bin": { "bytebase-mcp": "dist/index.js" diff --git a/package.json b/package.json index a8603c9..3743cae 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "@bytebase/bytebase-mcp", "version": "0.1.0", "mcpName": "io.github.bytebase/bytebase-mcp", - "description": "Official MCP server package for Bytebase. Ships the tool definitions of Bytebase's built-in MCP server and forwards every call to your Bytebase instance over its OAuth-protected /mcp endpoint.", + "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": { "type": "git", "url": "https://github.com/bytebase/bytebase-mcp.git" @@ -29,7 +29,7 @@ "build": "tsc && node scripts/copy-assets.mjs", "start": "node dist/index.js", "typecheck": "tsc --noEmit", - "test": "node --test test/config.test.mjs test/smoke.test.mjs", + "test": "node --test test/config.test.mjs test/browser.test.mjs test/smoke.test.mjs test/sessions.test.mjs", "sync-tools": "node scripts/sync-tools.mjs", "render-readme": "node scripts/render-readme.mjs", "sync-version": "node scripts/sync-version.mjs", @@ -49,7 +49,7 @@ "mysql" ], "dependencies": { - "@modelcontextprotocol/sdk": "^1.32.2" + "@modelcontextprotocol/sdk": "1.32.2" }, "devDependencies": { "@types/node": "^22.13.10", diff --git a/scripts/check-live.mjs b/scripts/check-live.mjs index 6e73232..4b46a38 100644 --- a/scripts/check-live.mjs +++ b/scripts/check-live.mjs @@ -1,5 +1,8 @@ // Manual end-to-end check against a real instance: starts dist/index.js the way // an MCP client would, lists tools, and runs two read-only calls through it. +// Signed out, the first list is empty and the browser sign-in opens as soon as +// the server starts, with the first call waiting for it; with a stored sign-in +// the instance's tools are listed at once. // BYTEBASE_URL=https://your-bytebase node scripts/check-live.mjs import path from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; @@ -15,12 +18,12 @@ const client = new Client({ name: "check-live", version: "0" }, { capabilities: await client.connect(transport); console.log("instructions:", JSON.stringify((client.getInstructions() ?? "").slice(0, 100))); const first = await client.listTools(); -console.log(`tools/list (bundled): ${first.tools.length}`); +console.log(`tools/list at start: ${first.tools.length} (0 while signed out)`); const search = await client.callTool({ name: "search_api", arguments: { service: "ProjectService" } }); console.log(`search_api: isError=${search.isError ?? false}`, search.content[0].text.slice(0, 160).replace(/\n/g, " | ")); const call = await client.callTool({ name: "call_api", arguments: { operationId: "ProjectService/ListProjects", body: { pageSize: 3 } } }); console.log(`call_api: isError=${call.isError ?? false}`, call.content[0].text.slice(0, 300).replace(/\n/g, " | ")); await new Promise((r) => setTimeout(r, 1000)); const second = await client.listTools(); -console.log(`tools/list (live): ${second.tools.length}`); +console.log(`tools/list after the calls: ${second.tools.length} (the instance's tools)`); await client.close(); diff --git a/scripts/copy-assets.mjs b/scripts/copy-assets.mjs index 2ae082e..25abbdf 100644 --- a/scripts/copy-assets.mjs +++ b/scripts/copy-assets.mjs @@ -1,9 +1,8 @@ -// Copies the generated tool definitions next to the compiled output, where -// src/tools.ts reads them at runtime (import.meta.url relative). +// Copies the bundled snapshot next to the compiled output, where src/tools.ts +// reads it, and marks the entry point executable, since npm links it as a bin. import fs from "node:fs"; import path from "node:path"; const root = path.join(import.meta.dirname, ".."); -fs.mkdirSync(path.join(root, "dist"), { recursive: true }); fs.copyFileSync(path.join(root, "src", "tools.json"), path.join(root, "dist", "tools.json")); fs.chmodSync(path.join(root, "dist", "index.js"), 0o755); diff --git a/scripts/sync-tools.mjs b/scripts/sync-tools.mjs index d1164f5..2491ed6 100644 --- a/scripts/sync-tools.mjs +++ b/scripts/sync-tools.mjs @@ -1,4 +1,6 @@ -// Regenerates src/tools.json from a running Bytebase instance. +// Regenerates src/tools.json, the snapshot an unconfigured proxy lists so MCP +// directories can show Bytebase's tools, from a running Bytebase instance. A +// configured proxy never reads it (docs/DESIGN.md, D2, D3). // // Bytebase's built-in MCP server answers tools/list only to a signed-in // session, so this connects the same way the package does (OAuth in the @@ -27,6 +29,7 @@ if (!config.url) { const upstream = new Upstream( { ...config, url: config.url }, + { name: "bytebase-mcp-sync-tools", title: "Bytebase MCP snapshot sync", version: "0" }, { // Declare a form so Bytebase serves the instructions written for clients that can confirm. clientCapabilities: () => ({ elicitation: { form: {} } }), @@ -34,10 +37,17 @@ const upstream = new Upstream( }, ); -const client = await upstream.get(); +const client = await upstream.open({ interactive: true, waitForLock: true }); const serverInfo = client.getServerVersion(); const rawInstructions = client.getInstructions() ?? ""; -const { tools } = await upstream.listTools(); +// Every page: the instance chooses its page size. +const tools = []; +let cursor; +do { + const page = await upstream.listTools(cursor); + tools.push(...page.tools); + cursor = page.nextCursor; +} while (cursor); upstream.reset(); let instructions = rawInstructions; diff --git a/server.json b/server.json index e125084..3736f7e 100644 --- a/server.json +++ b/server.json @@ -27,7 +27,7 @@ }, { "name": "BYTEBASE_MCP_HOME", - "description": "Directory for the OAuth token files (default: ~/.config/bytebase-mcp)", + "description": "Directory for the OAuth sign-ins (default: ~/.bytebase-mcp)", "isRequired": false, "format": "string", "isSecret": false diff --git a/src/auth.ts b/src/auth.ts index 2b1be6f..97ef1e9 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,58 +1,115 @@ import fs from "node:fs"; import http from "node:http"; import path from "node:path"; +import { AsyncLocalStorage } from "node:async_hooks"; import { randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; -import type { - OAuthClientInformationMixed, - OAuthClientMetadata, - OAuthTokens, -} from "@modelcontextprotocol/sdk/shared/auth.js"; +import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; +import type { Implementation } from "@modelcontextprotocol/sdk/types.js"; +import { browserCommand } from "./browser.js"; +import { FileLock } from "./lock.js"; import { log } from "./log.js"; interface StoredState { clientInformation?: OAuthClientInformationMixed; tokens?: OAuthTokens; - codeVerifier?: string; +} + +/** Bytebase rejects a longer client_name (backend/api/oauth2/register.go). */ +const MAX_CLIENT_NAME = 200; + +/** The client application a sign-in belongs to (docs/DESIGN.md, D6). */ +export interface ClientIdentity { + /** File name for its sign-in. */ + key: string; + /** What Bytebase shows on the consent page. */ + clientName: string; +} + +export function clientIdentity(info: Implementation | undefined): ClientIdentity { + const name = info?.name?.trim() || "unknown-client"; + const label = info?.title?.trim() || name; + return { + key: name.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 100), + clientName: `${label} via Bytebase MCP`.slice(0, MAX_CLIENT_NAME), + }; +} + +/** Directory holding an instance's sign-ins: host, port and path, so instances under different paths do not collide. */ +export function instanceDir(home: string, instanceUrl: URL): string { + const key = `${instanceUrl.hostname}${instanceUrl.port ? `_${instanceUrl.port}` : ""}${instanceUrl.pathname.replace(/\/+$/, "")}`; + return path.join(home, key.replace(/[^A-Za-z0-9._-]/g, "_")); +} + +/** A sign-in was needed where the proxy may not start one (docs/DESIGN.md, D7). */ +export class SignInRequiredError extends Error { + constructor(message = "sign-in needed") { + super(message); + this.name = "SignInRequiredError"; + } } export interface FileOAuthClientProviderOptions { - /** Directory that holds one token file per instance host. */ home: string; - /** Loopback port the authorization redirect comes back on. */ callbackPort: number; - /** Open the authorization URL in the default browser. The URL is printed to stderr either way. */ openBrowser: boolean; - /** How long to wait for the user to finish signing in. */ signInTimeoutMs?: number; } /** - * Keeps the OAuth client registration, tokens and PKCE verifier for one - * Bytebase instance in a 0600 file under `home`, and runs the browser leg of - * the authorization-code flow on a loopback listener. - * - * The MCP SDK drives the rest: discovery through the instance's - * `/.well-known/oauth-protected-resource/mcp`, dynamic client registration, - * PKCE, token exchange and refresh. + * Marks work done while this async chain holds a sign-in's lock, so it does not + * wait on itself. Work the holder starts can outlive it (the SDK's event stream + * does), so the mark counts only while `active` is true. + */ +const lockHeld = new AsyncLocalStorage<{ file: string; active: boolean }>(); + +/** + * One session opening that may start a browser sign-in (D7), and the state of + * that sign-in. The state lives here, not on the shared provider, so nothing + * outside the opening (a retired session's own OAuth attempt) can overwrite + * it. A session the opening starts can outlive it, so this counts only while + * `active` is true. + */ +export interface SignInPermit { + active: boolean; + /** Set once this opening's browser leg starts; after that a failure is a failed sign-in (D5). */ + browserOpened?: boolean; + state?: string; + verifier?: string; + pendingCode?: Promise; +} + +export const signInPermitted = new AsyncLocalStorage(); + +/** The permit of the opening this work belongs to, if it is still in progress. */ +function activePermit(): SignInPermit | undefined { + const permit = signInPermitted.getStore(); + return permit?.active ? permit : undefined; +} + +/** + * Keeps one client application's sign-in to one Bytebase instance in a 0600 + * file, under the rules of docs/DESIGN.md D7: the file is written only while + * holding its lock; signing in and refreshing each run under it; the PKCE + * verifier stays in memory; a refused credential is deleted only if the file + * still holds what this process sent. */ export class FileOAuthClientProvider implements OAuthClientProvider { - private readonly file: string; + readonly file: string; + private readonly lock: FileLock; private readonly options: Required; - private state_: StoredState; - private pendingState?: string; - private pendingCode?: Promise; + private readonly identity: ClientIdentity; + private lastSentRefreshToken?: string; + /** The access token the instance last refused, to tell newer tokens on disk from the rejected ones. */ + private lastRejectedAccessToken?: string; - constructor(instanceUrl: URL, options: FileOAuthClientProviderOptions) { + constructor(instanceUrl: URL, identity: ClientIdentity, options: FileOAuthClientProviderOptions) { this.options = { signInTimeoutMs: 5 * 60 * 1000, ...options }; - const hostKey = `${instanceUrl.hostname}${instanceUrl.port ? `_${instanceUrl.port}` : ""}`.replace(/[^A-Za-z0-9._-]/g, "_"); - this.file = path.join(options.home, `${hostKey}.json`); - this.state_ = this.read(); - } - - get tokenFile(): string { - return this.file; + this.identity = identity; + this.file = path.join(instanceDir(options.home, instanceUrl), `${identity.key}.json`); + this.lock = new FileLock(this.file); } get redirectUrl(): string { @@ -61,7 +118,7 @@ export class FileOAuthClientProvider implements OAuthClientProvider { get clientMetadata(): OAuthClientMetadata { return { - client_name: "Bytebase MCP (npm)", + client_name: this.identity.clientName, client_uri: "https://github.com/bytebase/bytebase-mcp", redirect_uris: [this.redirectUrl], grant_types: ["authorization_code", "refresh_token"], @@ -70,101 +127,180 @@ export class FileOAuthClientProvider implements OAuthClientProvider { }; } + /** Whether the file holds tokens, without opening anything. */ + hasStoredSignIn(): boolean { + return Boolean(this.read().tokens); + } + + /** + * Runs fn while holding the sign-in's lock. With `wait: false` it returns + * undefined at once when another holder has the lock. + */ + async withLock(fn: () => Promise, { wait }: { wait: boolean }): Promise<{ value: T } | undefined> { + const held = lockHeld.getStore(); + if (held?.active && held.file === this.file) return { value: await fn() }; + const release = await this.lock.acquire({ wait }); + if (!release) return undefined; + const mark = { file: this.file, active: true }; + try { + return { value: await lockHeld.run(mark, fn) }; + } finally { + mark.active = false; + release(); + } + } + state(): string { - this.pendingState = randomBytes(16).toString("hex"); - return this.pendingState; + const value = randomBytes(16).toString("hex"); + const permit = activePermit(); + if (permit) permit.state = value; + return value; } clientInformation(): OAuthClientInformationMixed | undefined { - return this.state_.clientInformation; + return this.read().clientInformation; } - saveClientInformation(clientInformation: OAuthClientInformationMixed): void { - this.state_.clientInformation = clientInformation; - this.write(); + async saveClientInformation(clientInformation: OAuthClientInformationMixed): Promise { + await this.writeUnderLock((state) => { + state.clientInformation = clientInformation; + }); } tokens(): OAuthTokens | undefined { - // Re-read: another bytebase-mcp process (MCP clients start one per session) - // may have refreshed the single-use refresh token since we last looked. - this.state_ = this.read(); - return this.state_.tokens; + return this.read().tokens; } - saveTokens(tokens: OAuthTokens): void { - this.state_.tokens = tokens; - this.write(); + async saveTokens(tokens: OAuthTokens): Promise { + await this.writeUnderLock((state) => { + // The fetch wrapper already wrote a refresh's result; only the SDK's issuer stamp may be new. + if (state.tokens?.access_token === tokens.access_token) { + state.tokens = { ...state.tokens, ...tokens }; + return; + } + state.tokens = tokens; + }); } saveCodeVerifier(codeVerifier: string): void { - this.state_.codeVerifier = codeVerifier; - this.write(); + const permit = activePermit(); + if (permit) permit.verifier = codeVerifier; } codeVerifier(): string { - const verifier = this.state_.codeVerifier; - if (!verifier) { - throw new Error("No PKCE code verifier saved; restart the sign-in"); - } + const verifier = activePermit()?.verifier; + if (!verifier) throw new Error("No PKCE code verifier for this sign-in; restart the sign-in"); return verifier; } - invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): void { - switch (scope) { - case "all": - this.state_ = {}; - break; - case "client": - delete this.state_.clientInformation; - break; - case "tokens": - delete this.state_.tokens; - break; - case "verifier": - delete this.state_.codeVerifier; - break; - case "discovery": - break; + async invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise { + if (scope === "verifier") { + const permit = activePermit(); + if (permit) permit.verifier = undefined; + return; } - this.write(); + if (scope === "discovery") return; + const sent = this.lastSentRefreshToken; + await this.writeUnderLock((state) => { + // Another process may have replaced what this one sent; leave its credentials alone. + if (state.tokens && sent && state.tokens.refresh_token !== sent) return; + if (scope === "tokens" || scope === "all") delete state.tokens; + if (scope === "client" || scope === "all") delete state.clientInformation; + }); } - /** Forgets everything stored for this instance. */ - clear(): void { - this.state_ = {}; - if (fs.existsSync(this.file)) { - fs.unlinkSync(this.file); - } + /** Forgets this sign-in. */ + async clear(): Promise { + await this.withLock(async () => fs.rmSync(this.file, { force: true }), { wait: true }); } /** - * Called by the SDK when a sign-in is needed. Starts the loopback listener, - * then hands the URL to the browser. The SDK throws UnauthorizedError right - * after; the caller then awaits {@link waitForAuthorizationCode}. + * The fetch the SDK transport sends through. A refresh runs under the lock + * from the request until its result is on disk; the SDK built the request + * from tokens it read earlier, so a request whose refresh token is no longer + * on disk is answered with the tokens on disk instead of being sent. + */ + readonly fetch: FetchLike = async (input, init) => { + const sent = refreshTokenIn(init); + if (!sent) { + const response = await fetch(input, init); + if (response.status === 401) this.lastRejectedAccessToken = bearerIn(init) ?? this.lastRejectedAccessToken; + return response; + } + this.lastSentRefreshToken = sent; + const held = await this.withLock( + async () => { + const onDisk = this.read().tokens; + const newerOnDisk = + onDisk?.refresh_token !== undefined && + (onDisk.refresh_token !== sent || (this.lastRejectedAccessToken !== undefined && onDisk.access_token !== this.lastRejectedAccessToken)); + if (onDisk && newerOnDisk) { + this.lastSentRefreshToken = onDisk.refresh_token; + const { issuer: _issuer, ...body } = onDisk as OAuthTokens & { issuer?: string }; + return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }); + } + const response = await fetch(input, init); + if (response.ok) { + const tokens = (await response.clone().json()) as OAuthTokens; + this.write({ ...this.read(), tokens }); + } + return response; + }, + { wait: true }, + ); + return held!.value; + }; + + /** + * Called by the SDK when a sign-in is needed. Refused unless a session is + * being opened for a tool call or S4; otherwise starts the loopback listener, + * under the machine-wide lock on the callback port, and hands the URL to the + * browser. */ async redirectToAuthorization(authorizationUrl: URL): Promise { - const expectedState = this.pendingState; - this.pendingCode = this.listenForCode(expectedState); + const permit = activePermit(); + if (!permit) throw new SignInRequiredError(); + permit.browserOpened = true; + const expectedState = permit.state; + const portLock = new FileLock(path.join(this.options.home, `callback-${this.options.callbackPort}`)); + const release = await portLock.acquire({ wait: true }); + const { listening, code } = this.listenForCode(expectedState); + permit.pendingCode = code.finally(() => release?.()); + // The URL is printed only once the callback can be received. + await listening; log(`Sign in to Bytebase to continue:\n ${authorizationUrl.toString()}`); - if (this.options.openBrowser) { - openInBrowser(authorizationUrl.toString()); - } + if (this.options.openBrowser) openInBrowser(authorizationUrl.toString()); } - /** Resolves with the authorization code once the browser redirects back. */ async waitForAuthorizationCode(): Promise { - if (!this.pendingCode) { - throw new Error("No sign-in in progress"); - } + const permit = activePermit(); + if (!permit?.pendingCode) throw new Error("No sign-in in progress"); try { - return await this.pendingCode; + return await permit.pendingCode; } finally { - this.pendingCode = undefined; + permit.pendingCode = undefined; } } - private listenForCode(expectedState: string | undefined): Promise { - return new Promise((resolve, reject) => { + private async writeUnderLock(change: (state: StoredState) => void): Promise { + await this.withLock( + async () => { + const state = this.read(); + change(state); + this.write(state); + }, + { wait: true }, + ); + } + + private listenForCode(expectedState: string | undefined): { listening: Promise; code: Promise } { + let onListening!: () => void; + let onListenFailed!: (err: Error) => void; + const listening = new Promise((resolve, reject) => { + onListening = resolve; + onListenFailed = reject; + }); + const code = new Promise((resolve, reject) => { const server = http.createServer((req, res) => { const url = new URL(req.url ?? "/", `http://127.0.0.1:${this.options.callbackPort}`); if (url.pathname !== "/callback") { @@ -176,7 +312,7 @@ export class FileOAuthClientProvider implements OAuthClientProvider { const state = url.searchParams.get("state"); if (error) { res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(page("Sign-in failed", `Bytebase answered: ${escapeHtml(error)}. You can close this tab.`)); - finish(new Error(`authorization refused: ${error}${url.searchParams.get("error_description") ? ` (${url.searchParams.get("error_description")})` : ""}`)); + finish(new Error(`authorization refused: ${error}`)); return; } if (!code) { @@ -191,31 +327,26 @@ export class FileOAuthClientProvider implements OAuthClientProvider { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(page("Signed in", "Bytebase MCP is connected. You can close this tab and return to your AI assistant.")); finish(undefined, code); }); - - const timer = setTimeout(() => { - finish(new Error(`sign-in timed out after ${Math.round(this.options.signInTimeoutMs / 1000)}s`)); - }, this.options.signInTimeoutMs); - + const timer = setTimeout(() => finish(new Error(`sign-in timed out after ${Math.round(this.options.signInTimeoutMs / 1000)}s`)), this.options.signInTimeoutMs); let done = false; const finish = (err: Error | undefined, code?: string) => { if (done) return; done = true; clearTimeout(timer); - // Let the response flush before closing. setTimeout(() => server.close(), 100); if (err) reject(err); else resolve(code as string); }; - server.on("error", (err: NodeJS.ErrnoException) => { - if (err.code === "EADDRINUSE") { - finish(new Error(`port ${this.options.callbackPort} is in use; set BYTEBASE_MCP_CALLBACK_PORT to a free port (the redirect URL registered with Bytebase must match, so clear ~/.config/bytebase-mcp if you change it)`)); - } else { - finish(err); - } + const failure = err.code === "EADDRINUSE" ? new Error(`port ${this.options.callbackPort} is in use; set BYTEBASE_MCP_CALLBACK_PORT to a free port and run \`bytebase-mcp logout\` so the new redirect URL is registered`) : err; + onListenFailed(failure); + finish(failure); }); - server.listen(this.options.callbackPort, "127.0.0.1"); + server.listen(this.options.callbackPort, "127.0.0.1", () => onListening()); }); + // A listen failure rejects both; the caller awaits `listening` first. + code.catch(() => undefined); + return { listening, code }; } private read(): StoredState { @@ -226,38 +357,38 @@ export class FileOAuthClientProvider implements OAuthClientProvider { } } - private write(): void { + private write(state: StoredState): void { fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 }); - const tmp = `${this.file}.${process.pid}.tmp`; - fs.writeFileSync(tmp, JSON.stringify(this.state_, null, 2) + "\n", { mode: 0o600 }); + const tmp = `${this.file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 }); fs.renameSync(tmp, this.file); } } +function bearerIn(init: RequestInit | undefined): string | undefined { + const header = new Headers(init?.headers).get("authorization"); + return header?.toLowerCase().startsWith("bearer ") ? header.slice("bearer ".length) : undefined; +} + +function refreshTokenIn(init: RequestInit | undefined): string | undefined { + if (!init || (init.method ?? "GET").toUpperCase() !== "POST" || !init.body) return undefined; + const body = init.body instanceof URLSearchParams ? init.body : typeof init.body === "string" ? new URLSearchParams(init.body) : undefined; + if (!body || body.get("grant_type") !== "refresh_token") return undefined; + return body.get("refresh_token") ?? undefined; +} + function openInBrowser(url: string): void { - let command: string; - let args: string[]; - switch (process.platform) { - case "darwin": - command = "open"; - args = [url]; - break; - case "win32": - command = "cmd"; - args = ["/c", "start", "", url.replace(/&/g, "^&")]; - break; - default: - command = "xdg-open"; - args = [url]; + const opener = browserCommand(url, process.platform); + if (!opener) { + log("the sign-in URL is not http(s); not opening it in a browser"); + return; } try { - const child = spawn(command, args, { stdio: "ignore", detached: true }); - child.on("error", () => { - /* the URL is already printed; nothing else to do */ - }); + const child = spawn(opener.command, opener.args, { stdio: "ignore", detached: true }); + child.on("error", () => undefined); child.unref(); } catch { - /* ignore: the URL is printed to stderr */ + /* the URL is printed to stderr */ } } diff --git a/src/browser.ts b/src/browser.ts new file mode 100644 index 0000000..772586d --- /dev/null +++ b/src/browser.ts @@ -0,0 +1,22 @@ +export interface BrowserCommand { + command: string; + args: string[]; +} + +/** + * How to open a sign-in URL on a platform, or undefined to only print it + * (docs/DESIGN.md, D5). The URL comes from the instance's OAuth metadata, so + * only http(s) is opened, and never through a shell: `cmd` would run what a + * `|` or `^` in the query introduces. + */ +export function browserCommand(url: string, platform: NodeJS.Platform): BrowserCommand | undefined { + if (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) return undefined; + switch (platform) { + case "darwin": + return { command: "open", args: [url] }; + case "win32": + return { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] }; + default: + return { command: "xdg-open", args: [url] }; + } +} diff --git a/src/config.ts b/src/config.ts index 554a02d..be5f061 100644 --- a/src/config.ts +++ b/src/config.ts @@ -14,10 +14,12 @@ export interface Config { export const DEFAULT_CALLBACK_PORT = 51789; +/** + * Where sign-ins live. They are credentials, not configuration, so not under + * ~/.config, which people often sync or keep in dotfile repositories. + */ export function defaultHome(): string { - const xdg = process.env.XDG_CONFIG_HOME; - const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), ".config"); - return path.join(base, "bytebase-mcp"); + return path.join(os.homedir(), ".bytebase-mcp"); } /** Normalizes a user-supplied Bytebase URL: trims, drops a trailing slash and a trailing /mcp. */ diff --git a/src/index.ts b/src/index.ts index 07b97a4..a5cec52 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,22 +2,28 @@ import { loadConfig } from "./config.js"; import { log } from "./log.js"; import { serveStdio } from "./server.js"; -import { Upstream, describe } from "./upstream.js"; +import { describe } from "./upstream.js"; +import { instanceDir } from "./auth.js"; +import { probeInstance } from "./probe.js"; +import { discoverOAuthServerInfo } from "@modelcontextprotocol/sdk/client/auth.js"; +import { FileLock } from "./lock.js"; +import { mcpEndpoint } from "./config.js"; +import fs from "node:fs"; +import path from "node:path"; import { PACKAGE_VERSION } from "./version.js"; const HELP = `bytebase-mcp ${PACKAGE_VERSION} -MCP server for Bytebase. Forwards tool calls to your Bytebase instance over its OAuth-protected /mcp endpoint. +MCP server for Bytebase. Reads the tool list from your Bytebase instance and forwards tool calls to its OAuth-protected /mcp endpoint. Usage: - bytebase-mcp [--url ] Serve MCP over stdio (default) - bytebase-mcp login [--url ] Sign in to the instance now and store the token - bytebase-mcp logout [--url ] Forget the stored sign-in for the instance - bytebase-mcp whoami [--url ] Show the instance, token file and tool count + bytebase-mcp [--url ] Serve MCP over stdio (default); signs in when the server starts + bytebase-mcp logout [--url ] Revoke and forget every sign-in stored for the instance + bytebase-mcp status [--url ] Show the instance and the stored sign-ins Environment: BYTEBASE_URL External URL of the Bytebase instance (required to call tools) - BYTEBASE_MCP_HOME Token directory (default ~/.config/bytebase-mcp) + BYTEBASE_MCP_HOME Sign-in directory (default ~/.bytebase-mcp) BYTEBASE_MCP_CALLBACK_PORT Loopback port for the OAuth redirect (default 51789) BYTEBASE_MCP_NO_BROWSER=1 Print the sign-in URL instead of opening a browser @@ -68,37 +74,32 @@ async function main(): Promise { if (!config.url) { throw new Error(`${command} needs a Bytebase URL: pass --url or set BYTEBASE_URL`); } - const upstream = new Upstream({ ...config, url: config.url }, { clientCapabilities: () => ({}) }); - + const dir = instanceDir(config.home, config.url); switch (command) { - case "login": { - const client = await upstream.get(); - const info = client.getServerVersion(); - log(`signed in to ${config.url} (Bytebase ${info?.version ?? "unknown"}); token stored at ${upstream.tokenFile}`); - upstream.reset(); - return; - } case "logout": - upstream.signOut(); - log(`removed ${upstream.tokenFile}`); + await logout(config.url, dir); return; - case "whoami": { - const client = await upstream.get(); - const info = client.getServerVersion(); - const tools = await upstream.listTools(); + case "status": { + const probe = await probeInstance(config.url, AbortSignal.timeout(5000)); + // A file left by an interrupted sign-in holds a registration but no tokens. + const signIns = fs.existsSync(dir) + ? fs + .readdirSync(dir) + .filter((name) => name.endsWith(".json") && hasTokens(path.join(dir, name))) + .map((name) => name.slice(0, -".json".length)) + : []; process.stdout.write( `${JSON.stringify( { url: config.url.toString(), - bytebaseVersion: info?.version, - tokenFile: upstream.tokenFile, - tools: tools.tools.map((t) => t.name), + bytebase: probe.kind === "bytebase" ? true : { answer: probe.kind, detail: probe.detail }, + signIns, + signInDirectory: dir, }, null, 2, )}\n`, ); - upstream.reset(); return; } default: @@ -110,3 +111,65 @@ main().catch((err) => { log(describe(err)); process.exit(1); }); + +function hasTokens(file: string): boolean { + try { + return Boolean((JSON.parse(fs.readFileSync(file, "utf8")) as { tokens?: unknown }).tokens); + } catch { + return false; + } +} + +/** How long logout waits on the instance for each request; the sign-ins are deleted either way. */ +const REVOKE_BOUND_MS = 5000; + +/** + * Forgets every sign-in stored for the instance. Each refresh token is revoked + * at the instance first, so a copy of the file stops working too; a sign-in is + * removed under its own lock, so it never races a refresh. + */ +async function logout(instanceUrl: URL, dir: string): Promise { + const instance = instanceUrl.toString().replace(/\/$/, ""); + const files = fs.existsSync(dir) ? fs.readdirSync(dir).filter((name) => name.endsWith(".json")) : []; + let revocationEndpoint: string | undefined; + try { + const info = await discoverOAuthServerInfo(mcpEndpoint(instanceUrl), { + fetchFn: (input, init) => fetch(input, { ...init, signal: AbortSignal.timeout(REVOKE_BOUND_MS) }), + }); + revocationEndpoint = (info.authorizationServerMetadata as { revocation_endpoint?: string } | undefined)?.revocation_endpoint; + } catch (err) { + log(`cannot reach ${instance} to revoke (${describe(err)}); the stored sign-ins are deleted and expire there on their own`); + } + for (const name of files) { + const file = path.join(dir, name); + const release = await new FileLock(file).acquire({ wait: true }); + try { + const stored = readStored(file); + const token = stored.tokens?.refresh_token; + const clientId = stored.clientInformation?.client_id; + if (revocationEndpoint && token && clientId) { + const response = await fetch(revocationEndpoint, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token, token_type_hint: "refresh_token", client_id: clientId }), + signal: AbortSignal.timeout(REVOKE_BOUND_MS), + }).catch((err: unknown) => err as Error); + if (response instanceof Error || !response.ok) { + log(`could not revoke ${name.slice(0, -".json".length)} at ${instance}; it expires there on its own`); + } + } + fs.rmSync(file, { force: true }); + } finally { + release?.(); + } + } + log(`removed ${files.length} sign-in(s) for ${instance} (${dir})`); +} + +function readStored(file: string): { tokens?: { refresh_token?: string }; clientInformation?: { client_id?: string } } { + try { + return JSON.parse(fs.readFileSync(file, "utf8")) as ReturnType; + } catch { + return {}; + } +} diff --git a/src/lock.ts b/src/lock.ts new file mode 100644 index 0000000..cd85cc4 --- /dev/null +++ b/src/lock.ts @@ -0,0 +1,100 @@ +import fs from "node:fs"; +import path from "node:path"; +import { randomBytes } from "node:crypto"; + +const POLL_MS = 50; + +/** Serializes holders of one lock within this process; the directory serializes processes. */ +const inProcess = new Map>(); + +/** + * A lock shared by processes on one machine: the directory `.lock`, + * created by renaming a directory that already holds the holder's process ID, + * so the lock never exists without an owner. A lock whose owner process is gone + * is abandoned and taken over. + */ +export class FileLock { + private readonly dir: string; + + constructor(target: string) { + this.dir = `${target}.lock`; + } + + /** + * Acquires the lock. With `wait: false` it gives up at once when another holder + * has it and returns undefined; otherwise it waits. + */ + async acquire({ wait }: { wait: boolean }): Promise<(() => void) | undefined> { + const previous = inProcess.get(this.dir); + if (previous && !wait) return undefined; + let releaseInProcess!: () => void; + const mine = new Promise((resolve) => (releaseInProcess = resolve)); + const chained = (previous ?? Promise.resolve()).then(() => mine); + inProcess.set(this.dir, chained); + await previous; + + try { + for (;;) { + if (this.tryCreate()) break; + if (this.ownerIsGone()) { + fs.rmSync(this.dir, { recursive: true, force: true }); + continue; + } + if (!wait) { + this.finish(chained, releaseInProcess); + return undefined; + } + await new Promise((resolve) => setTimeout(resolve, POLL_MS)); + } + } catch (err) { + this.finish(chained, releaseInProcess); + throw err; + } + + let released = false; + return () => { + if (released) return; + released = true; + fs.rmSync(this.dir, { recursive: true, force: true }); + this.finish(chained, releaseInProcess); + }; + } + + private finish(chained: Promise, releaseInProcess: () => void): void { + releaseInProcess(); + if (inProcess.get(this.dir) === chained) inProcess.delete(this.dir); + } + + private tryCreate(): boolean { + fs.mkdirSync(path.dirname(this.dir), { recursive: true, mode: 0o700 }); + const staging = `${this.dir}.${process.pid}.${randomBytes(4).toString("hex")}`; + fs.mkdirSync(staging, { mode: 0o700 }); + fs.writeFileSync(path.join(staging, "pid"), String(process.pid)); + try { + fs.renameSync(staging, this.dir); + return true; + } catch (err) { + fs.rmSync(staging, { recursive: true, force: true }); + const code = (err as NodeJS.ErrnoException).code; + if (code === "EEXIST" || code === "ENOTEMPTY" || code === "EPERM") return false; + throw err; + } + } + + private ownerIsGone(): boolean { + let pid: number; + try { + pid = Number.parseInt(fs.readFileSync(path.join(this.dir, "pid"), "utf8"), 10); + } catch { + // Mid-release, or gone already: look again on the next poll. + return false; + } + if (!Number.isInteger(pid) || pid === process.pid) return false; + try { + process.kill(pid, 0); + return false; + } catch (err) { + return (err as NodeJS.ErrnoException).code === "ESRCH"; + } + } +} diff --git a/src/probe.ts b/src/probe.ts new file mode 100644 index 0000000..5ffe161 --- /dev/null +++ b/src/probe.ts @@ -0,0 +1,51 @@ +import { mcpEndpoint } from "./config.js"; + +/** What the instance's protected-resource document says about the configured URL. */ +export type InstanceProbe = + | { kind: "bytebase" } + /** The server answered, with anything but Bytebase's document for this URL. */ + | { kind: "not-bytebase"; detail: string } + /** No answer (network error or timeout), or a gateway's 502, 503 or 504. */ + | { kind: "unreachable"; detail: string }; + +/** A reverse proxy's answer while the Bytebase behind it is down or restarting (docs/DESIGN.md, States). */ +export function isGatewayStatus(status: unknown): boolean { + return status === 502 || status === 503 || status === 504; +} + +/** + * Asks GET /.well-known/oauth-protected-resource/mcp. A Bytebase instance + * with MCP answers with a document whose `resource` is /mcp. + */ +export async function probeInstance(base: URL, signal?: AbortSignal): Promise { + const endpoint = mcpEndpoint(base); + const url = new URL(endpoint.toString()); + url.pathname = `/.well-known/oauth-protected-resource${endpoint.pathname}`; + let response: Response; + try { + response = await fetch(url, { signal, headers: { Accept: "application/json" } }); + } catch (err) { + return { kind: "unreachable", detail: errorText(err) }; + } + if (!response.ok) { + await response.body?.cancel(); + const detail = `HTTP ${response.status} for ${url.pathname}`; + return isGatewayStatus(response.status) ? { kind: "unreachable", detail } : { kind: "not-bytebase", detail }; + } + try { + const body = (await response.json()) as { resource?: unknown }; + const expected = endpoint.toString().replace(/\/+$/, ""); + if (typeof body.resource === "string" && body.resource.replace(/\/+$/, "") === expected) return { kind: "bytebase" }; + return { kind: "not-bytebase", detail: `its protected-resource document names ${String(body.resource)}, not ${expected}` }; + } catch { + return { kind: "not-bytebase", detail: `${url.pathname} is not a protected-resource document` }; + } +} + +function errorText(err: unknown): string { + if (err instanceof Error) { + const cause = (err as Error & { cause?: unknown }).cause; + return cause instanceof Error ? `${err.message} (${cause.message})` : err.message; + } + return String(err); +} diff --git a/src/retry.ts b/src/retry.ts new file mode 100644 index 0000000..1fb4f93 --- /dev/null +++ b/src/retry.ts @@ -0,0 +1,13 @@ +const FIRST_MS = 1000; +const CEILING_MS = 5 * 60 * 1000; +const RETRIES = 10; + +/** + * The waits before each retry of opening a session when the instance cannot be + * reached at startup (docs/DESIGN.md, D5): doubling from one second up to a + * five-minute ceiling, ten retries in all, after which the proxy stops until + * the client restarts it. + */ +export function startupRetryDelaysMs(): number[] { + return Array.from({ length: RETRIES }, (_, i) => Math.min(FIRST_MS * 2 ** i, CEILING_MS)); +} diff --git a/src/server.ts b/src/server.ts index 94ffc0b..bb4f80c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2,123 +2,253 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, + ErrorCode, + InitializeRequestSchema, ListToolsRequestSchema, McpError, type CallToolResult, - type ListToolsResult, + type ClientCapabilities, + type InitializeRequest, + type InitializeResult, } from "@modelcontextprotocol/sdk/types.js"; import type { Config } from "./config.js"; import { log } from "./log.js"; +import { isGatewayStatus, probeInstance, type InstanceProbe } from "./probe.js"; +import { startupRetryDelaysMs } from "./retry.js"; import { loadBundledTools } from "./tools.js"; -import { Upstream, describe } from "./upstream.js"; +import { NO_TIMEOUT_MS, Upstream, describe, isFailedSignIn } from "./upstream.js"; import { PACKAGE_VERSION } from "./version.js"; +/** How long initialize waits for a stored sign-in or the instance probe (docs/DESIGN.md, D4). */ +const INITIALIZE_BOUND_MS = 5000; +/** How long tools/list waits to reopen a dropped session before answering with an error. */ +const LIST_BOUND_MS = 10_000; + /** - * Used when the Bytebase release the bundle was read from sent no initialize - * instructions (releases before the server shipped them). Newer dumps carry - * Bytebase's own text, which wins. + * Runs work with a deadline; on expiry it aborts the work's signal, calls + * onExpiry and rejects with reason. */ -const FALLBACK_INSTRUCTIONS = `Bytebase governs access to databases and changes to them. Every call is also limited by the signed-in account's permissions and the workspace's MCP access policy. +async function withinBound(work: (signal: AbortSignal) => Promise, ms: number, onExpiry: () => void, reason: string): Promise { + const controller = new AbortController(); + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { + controller.abort(); + onExpiry(); + reject(new Error(reason)); + }, ms); + }); + const running = work(controller.signal); + running.catch(() => undefined); + try { + return await Promise.race([running, timeout]); + } finally { + clearTimeout(timer); + } +} -Choose the tool by task: -- Read data: query_database. Before you write SQL for a database, read its schema with get_schema. -- Inspect a schema: get_schema. -- Change a database: propose_database_change. It creates the plan and the issue and runs the plan checks; approval and rollout follow the project's policy. -- Anything else: search_api to find the operation and its request schema, then call_api. +/** Network errors: the instance gave no answer at all. */ +function isUnreachable(err: unknown): boolean { + // The SDK's transport error carries the HTTP status as its code, wrapped as a cause; its OAuth + // discovery errors carry it only in their text ("HTTP 503 trying to load ... metadata"). + for (let e: unknown = err; e instanceof Error; e = e.cause) { + if (isGatewayStatus((e as Error & { code?: unknown }).code)) return true; + } + if (/\bHTTP 50[234] trying to load\b/.test(describe(err))) return true; + return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|fetch failed/i.test(describe(err)); +} -When Bytebase refuses a call, the error states the reason and may name a next step.`; +const NO_INSTANCE_NOTE = + "No Bytebase instance is connected, so these tools cannot run yet. Set BYTEBASE_URL to your Bytebase external URL (for example https://bytebase.example.com) in the MCP server's environment and restart the server. See https://docs.bytebase.com/integrations/mcp"; -const NO_INSTANCE_MESSAGE = - "No Bytebase instance is configured. Set BYTEBASE_URL to your Bytebase external URL (for example https://bytebase.example.com) in the MCP server's environment and restart the server. See https://docs.bytebase.com/integrations/mcp"; +const REAUTHORIZE_NOTE = "Through bytebase-mcp, reconnect this MCP server in your client and sign in as the account you want."; + +/** The package's version of the instance's form paragraph, for states where that text cannot be read. */ +const FORM_SENTENCE = + "This client cannot show Bytebase's confirmation form, so before you run a statement that may write, show it to the user and ask them to confirm."; + +/** The instance's own rule (declaresFormElicitation in Bytebase's tool_resolve.go). */ +function declaresForm(capabilities: ClientCapabilities | undefined): boolean { + const elicitation = capabilities?.elicitation; + if (!elicitation) return false; + return Boolean(elicitation.form) || !elicitation.url; +} + +/** 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.` + : 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).`; + return declaresForm(capabilities) ? text : `${text}\n\n${FORM_SENTENCE}`; +} /** - * Builds the stdio MCP server. It answers initialize and tools/list on its own - * from the bundled definitions, so a directory can read them without an - * instance, and forwards tools/call (and the confirmation forms Bytebase sends - * back) to the configured instance. + * 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). */ -export function createServer(config: Config): { server: Server; upstream?: Upstream } { - const bundled = loadBundledTools(); - +export function createServer(config: Config): { server: Server; upstream: () => Upstream | undefined } { const server = new Server( { name: "bytebase", title: "Bytebase", version: PACKAGE_VERSION }, - { - capabilities: { tools: { listChanged: true } }, - instructions: bundled.instructions.trim().length > 0 ? bundled.instructions : FALLBACK_INSTRUCTIONS, - }, + { capabilities: { tools: { listChanged: true } } }, ); + // Requests to the client are numbered from 1: the SDK numbers from 0, and its + // own cancellation handler ignores request ID 0 (`if (!requestId) return`), so a + // client on this SDK would keep the first withdrawn form up (D5). + (server as unknown as { _requestMessageId: number })._requestMessageId = 1; + let initialized = false; + // Created at initialize: a sign-in belongs to the client application (D6). let upstream: Upstream | undefined; - let liveTools: ListToolsResult | undefined; - - if (config.url) { - upstream = new Upstream( - { ...config, url: config.url }, - { - clientCapabilities: () => server.getClientCapabilities() ?? {}, - onElicit: (params) => server.elicitInput(params), - onToolListChanged: () => { - liveTools = undefined; - void refreshLiveTools(); - }, - }, - ); + const upstreamFor = (url: URL): Upstream => { + upstream ??= new Upstream({ ...config, url }, server.getClientVersion(), { + clientCapabilities: () => server.getClientCapabilities() ?? {}, + // Bytebase decides how long a form stays up, and may withdraw it (D5). + onElicit: (params, signal) => server.elicitInput(params, { signal, timeout: NO_TIMEOUT_MS }), + onToolListChanged: () => void server.sendToolListChanged().catch(() => undefined), + }); + return upstream; + }; + + /** Opens the session, then tells the client its tool list changed from empty. */ + async function openAndAnnounce(url: URL, interactive: boolean): Promise { + const target = upstreamFor(url); + const hadSession = Boolean(target.session); + await target.open({ interactive, waitForLock: true }); + if (!hadSession && initialized) await server.sendToolListChanged(); } - /** Fetches the live tool list in the background and tells the client when it differs from what it has. */ - async function refreshLiveTools(): Promise { - if (!upstream) return; - try { - const fresh = await upstream.listTools(); - const changed = JSON.stringify(fresh.tools) !== JSON.stringify((liveTools ?? bundled).tools); - liveTools = fresh; - if (changed) { - await server.sendToolListChanged(); + // Decorates the SDK's own initialize answer, which also records the client's + // capabilities, with instructions for the state the proxy is in. + const sdkInitialize = (server as unknown as { _oninitialize(request: InitializeRequest): Promise })._oninitialize.bind(server); + server.setRequestHandler(InitializeRequestSchema, async (request) => { + const result = await sdkInitialize(request); + if (!config.url) { + const snapshot = loadBundledTools(); + return { ...result, instructions: [NO_INSTANCE_NOTE, snapshot.instructions].filter((part) => part.trim().length > 0).join("\n\n") }; + } + const target = upstreamFor(config.url); + // Both run within the bound: the probe decides the signed-out text if no session opens. + const probing = probeInstance(config.url, AbortSignal.timeout(INITIALIZE_BOUND_MS)); + // S2: a stored sign-in opens the session without waiting for the lock or asking the user. + if (target.provider.hasStoredSignIn()) { + const opening = target.open({ interactive: false, waitForLock: false }); + const timeout = new Promise((resolve) => setTimeout(() => resolve(undefined), INITIALIZE_BOUND_MS).unref()); + const session = await Promise.race([opening.catch((err) => log(`starting signed out: ${describe(err)}`)), timeout]); + if (session) return { ...result, instructions: session.getInstructions() ?? "" }; + } + const probe = await probing; + return { ...result, instructions: signedOutInstructions(config.url.toString().replace(/\/$/, ""), probe, request.params.capabilities) }; + }); + + server.oninitialized = () => { + initialized = true; + // A configured proxy without a session has no tools to offer, so it signs in now (D5). + if (!config.url || upstream?.session) return; + void signInWhenReachable(config.url); + }; + + let announcing = false; + /** After a tools/list gave up waiting, announces the list once the reopen it started opens. */ + function announceWhenOpen(target: Upstream): void { + if (announcing) return; + announcing = true; + target + .open({ interactive: false, waitForLock: true }) + .then(() => server.sendToolListChanged()) + .catch((err) => log(`the session did not reopen: ${describe(err)}`)) + .finally(() => { + announcing = false; + }); + } + + /** + * D5: an unreachable instance is retried on a fixed schedule, and the browser + * opens only once it answers. A sign-in that fails or times out is not + * restarted, and after the last retry the proxy stops until a client restart. + */ + async function signInWhenReachable(url: URL): Promise { + const instance = url.toString().replace(/\/$/, ""); + const waits = startupRetryDelaysMs(); + for (let attempt = 0; ; attempt++) { + try { + await openAndAnnounce(url, true); + return; + } catch (err) { + if (isFailedSignIn(err) || !isUnreachable(err)) { + log(`sign-in failed: ${describe(err)}`); + return; + } + const wait = waits[attempt]; + if (wait === undefined) { + log(`${instance} still cannot be reached after ${waits.length} retries; restart the client to try again`); + return; + } + log(`${instance} cannot be reached (${describe(err)}); retrying in ${Math.round(wait / 1000)}s`); + await new Promise((resolve) => setTimeout(resolve, wait).unref()); } - } catch (err) { - log(`could not read the live tool list, serving the bundled one (Bytebase ${bundled.bytebaseVersion}): ${describe(err)}`); } } - server.setRequestHandler(ListToolsRequestSchema, async () => { - if (liveTools) return liveTools; - if (upstream) { - // Never block the client's first tools/list on a sign-in: answer from the - // bundle and announce the live list once it arrives. - void refreshLiveTools(); + 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 + // is reopened here (D5), within a bound. + const target = upstreamFor(config.url); + if (!target.session && (target.signingIn || !target.provider.hasStoredSignIn())) return { 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, + // 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(/\/$/, "")}`); + } 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). + throw new McpError(ErrorCode.InternalError, `Bytebase MCP: ${describe(err)}`); } - return { tools: bundled.tools }; }); - server.setRequestHandler(CallToolRequestSchema, async (request): Promise => { - if (!upstream) { - return { isError: true, content: [{ type: "text", text: NO_INSTANCE_MESSAGE }] }; + server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { + if (!config.url) { + return { isError: true, content: [{ type: "text", text: NO_INSTANCE_NOTE }] }; } try { - return await upstream.callTool(request.params); + const hadSession = Boolean(upstream?.session); + const result = await upstreamFor(config.url).callTool(request.params, extra.signal); + if (!hadSession && initialized) void server.sendToolListChanged().catch(() => undefined); + // The one addition to a forwarded result (rule 4): the client keeps + // instructions naming the old account until it reinitializes. + if (request.params.name === "reauthorize" && !result.isError) { + return { ...result, content: [...result.content, { type: "text", text: REAUTHORIZE_NOTE }] }; + } + return result; } catch (err) { if (err instanceof McpError) throw err; - return { - isError: true, - content: [{ type: "text", text: `Bytebase MCP: ${describe(err)}` }], - }; + return { isError: true, content: [{ type: "text", text: `Bytebase MCP: ${describe(err)}` }] }; } }); - return { server, upstream }; + return { server, upstream: () => upstream }; } export async function serveStdio(config: Config): Promise { const { server, upstream } = createServer(config); const transport = new StdioServerTransport(); await server.connect(transport); - if (config.url) { - log(`forwarding to ${config.url.toString().replace(/\/$/, "")}/mcp`); - } else { - log("BYTEBASE_URL is not set: serving the bundled tool list only; tool calls will fail until it is set"); - } + log(config.url ? `forwarding to ${config.url.toString().replace(/\/$/, "")}/mcp` : "BYTEBASE_URL is not set: listing the bundled snapshot; tool calls fail until it is set"); const shutdown = () => { - upstream?.reset(); + upstream()?.reset(); + // A pending sign-in or a stalled close must not keep the process alive once the client left. + setTimeout(() => process.exit(0), 1000).unref(); void server.close().finally(() => process.exit(0)); }; process.on("SIGINT", shutdown); diff --git a/src/tools.json b/src/tools.json index 911c218..ddacebd 100644 --- a/src/tools.json +++ b/src/tools.json @@ -1,12 +1,33 @@ { "$comment": "Generated by scripts/sync-tools.mjs from a Bytebase instance's built-in MCP server. Do not edit by hand; rerun `npm run sync-tools`.", - "bytebaseVersion": "3.24.1", - "generatedAt": "2026-11-13T16:15:59.151Z", - "instructions": "", + "bytebaseVersion": "3.25.0", + "generatedAt": "2026-11-24T03:24:39.906Z", + "instructions": "Bytebase governs access to databases and changes to them. Every call is also limited by the workspace's MCP access policy.\n\nChoose the tool by task:\n- Find a database: call_api(operationId=\"DatabaseService/SearchDatabases\") lists the databases you can view.\n- Read data: query_database. Before you write SQL for a database, read its schema with get_schema.\n- Inspect a schema: get_schema.\n- Change a database: propose_database_change, the easiest way into the governed workflow. It creates the plan and the issue and runs the plan checks; approval and rollout follow the project's policy. It changes one database per call. For several databases in one plan, ask the user to use the Bytebase console or GitOps.\n- Anything else: a tool whose description covers the task; failing that, search_api to find the operation and its request schema, then call_api.\n\nWhen the workspace's MCP access policy is Read-write, query_database can also run DML and DDL, as far as the engine and the account's permissions allow; call_api refuses them. They take effect at once, without an issue or approval. Use propose_database_change for any change that should be reviewed, or when a write fails on a read-only data source.\n\nWhen Bytebase refuses a call, the error states the reason and may name a next step, such as a tool to use.", "tools": [ + { + "name": "administer_workspace", + "description": "Make a workspace administration change that the user confirms in this client first. It takes a Bytebase API operation and its request body, as search_api describes them.\n\n| Parameter | Required | Description |\n|-------------|----------|-------------|\n| operationId | Yes | The operation, e.g. \"SettingService/UpdateSetting\" |\n| body | Yes | The operation's request body |\n\nIt serves four changes.\n\nThe approval rules for database changes: send SettingService/UpdateSetting with setting.name \"settings/WORKSPACE_APPROVAL\" and the whole rule list in setting.value.workspaceApproval.rules. Read the stored rules first with call_api SettingService/GetSetting, change only the rules whose source is CHANGE_DATABASE, and send every other rule as stored, in its order. Give each rule you add the source CHANGE_DATABASE. Send a rule's source, condition.expression, template.title, template.description and template.flow.roles; other fields are refused. Name each approver in template.flow.roles by its role name, such as roles/workspaceDBA. An approval check tries the CHANGE_DATABASE rules in order, and the first whose condition matches decides who approves a change. When none matches, the rules with no source, such as the Fallback Rule, decide, and a change that no rule matches needs no approval.\n\nThe masking rules: send OrgPolicyService/UpdatePolicy with policy.name \"workspaces/{workspace}/policies/masking_rule\", policy.type MASKING_RULE and the whole rule list in policy.maskingRulePolicy.rules, with allowMissing true when no rules are stored yet. Read the stored rules first with call_api OrgPolicyService/GetPolicy, and the semantic types with call_api SettingService/GetSetting on settings/SEMANTIC_TYPES; the built-in types bb.default (full mask) and bb.default-partial (partial mask) always exist. Send a rule's id, condition.expression, condition.title and semanticType; other fields are refused, and the tool sets updateMask. Keep each stored rule's id, and give each new rule a new UUID. Masking tries the rules in order, and the first whose condition matches gives a column its semantic type; a column that no rule matches keeps its own.\n\nA PostgreSQL instance in a project: send InstanceService/CreateInstance with parent \"projects/{project}\", instanceId, and instance with title, engine POSTGRES, environment (\"environments/{id}\", or left out for none), activation, and one dataSources entry: type ADMIN, host, port, username, password, and optionally database, useSsl, verifyTlsCertificate and authenticationType PASSWORD; the tool sets its id. Other fields are refused, keys that name no field are ignored, and the default project cannot own an instance. Masking skips an instance that is not activated unless every instance is licensed; the create refuses activation true when no license is free, as on the Free plan. When the user accepts, Bytebase tests the connection and adds the instance only if it connects; its databases join the project for good.\n\nA workload identity for CI jobs in one GitHub or GitLab repository: send WorkloadIdentityService/CreateWorkloadIdentity in a project, with the fields search_api's note on it lists. When the user accepts, the tool creates it and grants it the GitOps Service Agent role in the project.\n\nThe tool shows the user what changes and asks them to confirm in a form. It makes the change only when they accept; declining or cancelling changes nothing. Do not ask in chat first: the form is the question.\n\nReading and changing the approval rules needs bb.settings.get and bb.settings.set, as in the console. Reading and changing the masking rules needs bb.policies.getMaskingRulePolicy and bb.policies.updateMaskingRulePolicy, bb.policies.createMaskingRulePolicy for the first save, and bb.settings.get for the semantic types. Adding an instance needs bb.instances.create, and a workload identity bb.workloadIdentities.create, bb.projects.getIamPolicy and bb.projects.setIamPolicy. call_api refuses each of these writes.", + "inputSchema": { + "type": "object", + "properties": { + "operationId": { + "type": "string" + }, + "body": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "operationId", + "body" + ], + "additionalProperties": false + } + }, { "name": "call_api", - "description": "Execute a Bytebase API endpoint. **Use search_api first to get operationId and schema.**\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| operationId | Yes | e.g., \"SQLService/Query\" |\n| body | No | JSON request body |\n\n**Resource names:** Preserve the exact canonical name returned by ListDatabases:\ninstances/prod/databases/main for a workspace instance, or\nprojects/my-project/instances/prod/databases/main for a project instance.\n\n**Example:**\ncall_api(operationId=\"SQLService/Query\", body={\"name\": \"projects/my-project/instances/i/databases/db\", \"statement\": \"SELECT 1\"})", + "description": "Execute a Bytebase API endpoint. **Use search_api first to get operationId and schema.**\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| operationId | Yes | e.g., \"SQLService/Query\" |\n| body | No | JSON request body |\n\n**Resource names:** Preserve the exact canonical name returned by SearchDatabases or ListDatabases:\ninstances/prod/databases/main for a workspace instance, or\nprojects/my-project/instances/prod/databases/main for a project instance.\n\n**Example:**\ncall_api(operationId=\"SQLService/Query\", body={\"name\": \"projects/my-project/instances/i/databases/db\", \"statement\": \"SELECT 1\"})", "inputSchema": { "type": "object", "properties": { @@ -47,9 +68,42 @@ "additionalProperties": false } }, + { + "name": "get_gitops_workflow", + "description": "Return the workflow files that set up GitOps for a project. With them in the repository, every pull request that changes the migration folder gets a Bytebase SQL review, and merging it deploys. The tool reads only; it changes nothing in Bytebase.\n\n| Parameter | Required | Description |\n|------------------|----------|-------------|\n| project | Yes | The project ID, e.g. \"hr\" |\n| targets | Yes | One database group (\"projects/hr/databaseGroups/all\"), or one or more databases by the name ListDatabases gives (\"instances/prod/databases/hr\") |\n| workloadIdentity | Yes | The email of the workload identity the jobs sign in as |\n| folder | No | The folder that holds the migration files. Default \"migrations\" |\n\nTo set up GitOps from the team's repository:\n1. Read the repository. The git remote gives the provider (GitHub or GitLab), the owner and the repository. Look for the folder that holds the SQL migration files.\n2. Ask the owner which databases to deploy to. List the project's database groups and databases with call_api (DatabaseGroupService/ListDatabaseGroups, DatabaseService/ListDatabases). Offer a group first: a database that joins it later is deployed with no change to the files, when its environment is one the files already deploy to.\n3. Find the workload identity with call_api WorkloadIdentityService/ListWorkloadIdentities on the project. Use one whose subject pattern names this repository. If there is none, create one with administer_workspace.\n4. Call this tool. Write each file at its path, and on GitLab add the include line the result gives to .gitlab-ci.yml. Ask before you replace a file that exists. Open a pull request into the default branch.\n\nThe jobs sign in with their own ID token, so the repository needs no secret. The workflows run only when a file in the migration folder changes, so the setup pull request runs neither, and the first pull request with a migration file is the test. With the GitOps Service Agent role, the identity's rollouts carry no issue, so no approval rule holds them: tell the owner that merging deploys.\n\nYou may fit the files to the repository, for example the runner, the stages, or how they join an existing pipeline. Keep BYTEBASE_URL, BYTEBASE_WORKLOAD_IDENTITY, the job permissions, the ID token settings, the action image, --project, --targets and the order of the deploy jobs. The identity admits every job in the repository, so the triggers alone decide which branch deploys: tell the owner before a change that lets another branch deploy.", + "inputSchema": { + "type": "object", + "properties": { + "project": { + "type": "string" + }, + "targets": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } + }, + "workloadIdentity": { + "type": "string" + }, + "folder": { + "type": "string" + } + }, + "required": [ + "project", + "targets", + "workloadIdentity" + ], + "additionalProperties": false + } + }, { "name": "get_schema", - "description": "Inspect a Bytebase database's schema.\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| database | Yes | Database name or substring (e.g., \"employee_db\" or \"employee\") |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| schema | No | Schema name for multi-schema engines (PG/MSSQL/Oracle/Snowflake/Redshift/CockroachDB/Databricks/Trino/Spanner/Hive); ignored with a note on MySQL/TiDB/etc. |\n| table | No | Drill into a single table; implies include=\"details\" |\n| include | No | Detail level: \"summary\" (default), \"columns\", \"details\" |\n\n**Usage:**\n- First call: get_schema(database=\"employee\") → compact overview\n- Drill down: get_schema(database=\"employee\", table=\"orders\") → full table detail\n- Write a query: get_schema(database=\"employee\", include=\"columns\") → all tables with columns\n\n**Notes:**\n- Metadata is auto-synced on access. The first call to a stale database may take longer.\n- For databases with many tables, columns/details modes return up to 200 tables PER SCHEMA.\n Use schema= or table= to narrow further.\n- Column masking metadata is only returned when table= is set.\n- Requires bb.databases.getSchema permission.", + "description": "Inspect a Bytebase database's schema.\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| database | Yes | Database name or substring (e.g., \"employee_db\" or \"employee\") |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| schema | No | Schema name for multi-schema engines (PG/MSSQL/Oracle/Snowflake/Redshift/CockroachDB/Databricks/Trino/Spanner/Hive); ignored with a note on MySQL/TiDB/etc. |\n| table | No | Drill into a single table; implies include=\"details\" |\n| include | No | Detail level: \"summary\" (default), \"columns\", \"details\" |\n\n**Usage:**\n- First call: get_schema(database=\"employee\") → compact overview\n- Drill down: get_schema(database=\"employee\", table=\"orders\") → full table detail\n- Write a query: get_schema(database=\"employee\", include=\"columns\") → all tables with columns\n\n**Notes:**\n- Metadata is auto-synced on access. The first call to a stale database may take longer.\n- For databases with many tables, columns/details modes return up to 200 tables PER SCHEMA.\n Use schema= or table= to narrow further.\n- Column masking metadata is only returned when table= is set.\n- rowCountEstimate is the row count the last metadata sync recorded. It can be an estimate, and can read 0 for a table that has rows; run a COUNT query when the number matters.\n- Requires bb.databases.getSchema permission.", "inputSchema": { "type": "object", "properties": { @@ -78,22 +132,9 @@ "additionalProperties": false } }, - { - "name": "get_skill", - "description": "Get step-by-step guides for Bytebase tasks.\n\n**Tip:** Use query_database for SQL queries and propose_database_change for single-database DDL/DML — they handle resolution automatically.\n\n**Workflow:** get_skill(\"task\") → search_api(operationId) → call_api(...)\n\nSkills: query, database-change", - "inputSchema": { - "type": "object", - "properties": { - "skill": { - "type": "string" - } - }, - "additionalProperties": false - } - }, { "name": "grant_masking_exemption", - "description": "Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table or column) or for every database in the project. The user confirms the exemption in this client first.\n\n| Parameter | Required | Description |\n|--------------|----------|-------------|\n| project | Yes | Project name, e.g. \"projects/hr\" |\n| member | Yes | \"user:{email}\", \"group:{email}\", \"serviceAccount:{email}\" or \"workloadIdentity:{email}\" |\n| database | One of | Database name, e.g. \"instances/prod/databases/hr\"; it must belong to the project |\n| allDatabases | One of | true for every database in the project, current and future |\n| schema | No | Narrow to one schema (needs database) |\n| table | No | Narrow to one table (needs database) |\n| column | No | Narrow to one column (needs table) |\n| expireTime | No | RFC 3339 time the exemption ends, e.g. \"2026-10-27T00:00:00Z\"; without it, it does not expire |\n| reason | No | Why, recorded with the exemption |\n\nAn exemption is a standing policy change: the member then sees the covered data unmasked in query and export results. For a one-off query, request an access grant instead (AccessGrantService/CreateAccessGrant).\n\nThe tool adds one exemption and leaves every other entry as it is. It shows the user the member, the scope, the expiry and the effect, and asks them to confirm in a form; it writes only when they accept. A client that cannot show the form gets the project's masking exemption page, to grant it in the Bytebase console instead. Do not ask in chat first: the form is the question.\n\nThe same permissions apply as in the console. This and revoke_masking_exemption are the only ways to change exemptions over MCP; call_api refuses OrgPolicyService/UpdatePolicy.", + "description": "Exempt one member from data masking in a Bytebase project, for one database (optionally one schema, table, or columns of one table) or for every database in the project. The user confirms the exemption in this client first.\n\n| Parameter | Required | Description |\n|--------------|----------|-------------|\n| project | Yes | Project name, e.g. \"projects/hr\" |\n| member | Yes | \"user:{email}\", \"group:{email}\", \"serviceAccount:{email}\" or \"workloadIdentity:{email}\" |\n| database | One of | Database name, e.g. \"instances/prod/databases/hr\"; it must belong to the project |\n| allDatabases | One of | true for every database in the project, current and future |\n| schema | No | Narrow to one schema (needs database) |\n| table | No | Narrow to one table (needs database) |\n| columns | No | Narrow to these columns of the table, e.g. [\"first_name\", \"last_name\"] (needs table) |\n| expireTime | No | RFC 3339 time the exemption ends, e.g. \"2026-10-27T00:00:00Z\"; without it, it does not expire |\n| reason | No | Why, recorded with the exemption |\n\nAn exemption is a standing policy change: the member bypasses the masking that applies to the covered data in query and export results, including masking set up later. It does not set up masking itself; administer_workspace changes the masking rules. For a one-off query, request an access grant instead with request_access_grant.\n\nThe tool adds one exemption and leaves every other entry as it is. For several columns of one table, pass them together in columns, so the user confirms once. It shows the user the member, the scope, the expiry and the effect, and asks them to confirm in a form; it writes only when they accept. A client that cannot show the form gets the project's masking exemption page, to grant it in the Bytebase console instead. Do not ask in chat first: the form is the question.\n\nThe same permissions apply as in the console. This and revoke_masking_exemption are the only ways to change exemptions over MCP; call_api refuses OrgPolicyService/UpdatePolicy.", "inputSchema": { "type": "object", "properties": { @@ -115,8 +156,14 @@ "table": { "type": "string" }, - "column": { - "type": "string" + "columns": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } }, "expireTime": { "type": "string" @@ -130,11 +177,14 @@ "member" ], "additionalProperties": false + }, + "_meta": { + "anthropic/requiresUserInteraction": true } }, { "name": "propose_database_change", - "description": "Run DDL/DML changes (ALTER TABLE, CREATE TABLE, INSERT, UPDATE, migrations) against a Bytebase database.\n\nThis is the primary tool for making database changes. Use this instead of manually calling CreateSheet/CreatePlan/CreateIssue via call_api.\n\nProvide plain SQL — the tool handles database resolution, sheet creation, plan creation with automatic plan checks, and issue creation in one call. Optionally creates a rollout.\n\n| Parameter | Required | Description |\n|---------------|----------|-------------|\n| database | Yes | Database name or substring |\n| sql | Yes | SQL statement(s) in plain text (NOT base64) |\n| title | Yes | Title for the issue/plan |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| changeType | No | \"MIGRATE\" (default) or \"SDL\" |\n| createRollout | No | If true, attempts rollout creation after issue |\n| reason | No | Context or ticket reference (max 1000 chars) |\n\n**Examples:**\npropose_database_change(database=\"app\", sql=\"ALTER TABLE users ADD COLUMN status VARCHAR(20)\", title=\"Add status column\")\npropose_database_change(database=\"app\", sql=\"UPDATE orders SET status='shipped' WHERE id=42\", title=\"Ship order 42\", createRollout=true)\n\n**Notes:**\n- v1 supports single database targets only. For batch changes across multiple databases, use get_skill(\"database-change\").\n- Plan checks run automatically; results included in response when available.\n- Requires bb.sheets.create, bb.plans.create, bb.issues.create permissions.\n- If createRollout=true but policy gates aren't satisfied, returns success with rolloutCreated=false and a reason.\n- nextAction AWAIT_HUMAN_APPROVAL means the issue waits for its approvers. If the user is one of them, decide_issue asks them to confirm in this client and then approves; otherwise share links.issue with an approver.\n- Masked data: a masked column reads back as \"******\". That is a placeholder, not a value anything holds. Any change containing it is refused, because writing it back would overwrite the real value. Ask a human to make the change in the Bytebase console instead.\n", + "description": "Run DDL/DML changes (ALTER TABLE, CREATE TABLE, INSERT, UPDATE, migrations) against a Bytebase database.\n\nThis is the primary tool for making database changes. Use this instead of manually calling CreateSheet/CreatePlan/CreateIssue via call_api.\n\nProvide plain SQL — the tool handles database resolution, sheet creation, plan creation with automatic plan checks, and issue creation in one call. Optionally creates a rollout.\n\n| Parameter | Required | Description |\n|---------------|----------|-------------|\n| database | Yes | Database name or substring |\n| sql | Yes | SQL statement(s) in plain text (NOT base64) |\n| title | Yes | Title for the issue/plan |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| changeType | No | \"MIGRATE\" (default) or \"SDL\" |\n| createRollout | No | If true, attempts rollout creation after issue |\n| reason | No | Context or ticket reference (max 1000 chars) |\n\n**Examples:**\npropose_database_change(database=\"app\", sql=\"ALTER TABLE users ADD COLUMN status VARCHAR(20)\", title=\"Add status column\")\npropose_database_change(database=\"app\", sql=\"UPDATE orders SET status='shipped' WHERE id=42\", title=\"Ship order 42\", createRollout=true)\n\n**Notes:**\n- It changes one database per call. For several databases in one plan, ask the user to use the Bytebase console or GitOps.\n- Plan checks run automatically; results included in response when available.\n- Requires bb.sheets.create, bb.plans.create, bb.issues.create permissions.\n- If createRollout=true but policy gates aren't satisfied, returns success with rolloutCreated=false and a reason.\n- nextAction AWAIT_HUMAN_APPROVAL means the issue waits for its approvers. If the user is one of them, decide_issue asks them to confirm in this client and then approves; otherwise share links.issue with an approver.\n- Masked data: a masked column reads back as \"******\". That is a placeholder, not a value anything holds. Any change containing it is refused, because writing it back would overwrite the real value. Ask a human to make the change in the Bytebase console instead.\n", "inputSchema": { "type": "object", "properties": { @@ -173,7 +223,7 @@ }, { "name": "query_database", - "description": "Execute a SQL query against a Bytebase database. Resolves the database by name automatically.\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| database | Yes | Database name or substring (e.g., \"employee_db\" or \"employee\") |\n| statement | Yes | SQL query to execute |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| schema | No | Default schema for unqualified names (Postgres search path). An access grant applies only when this equals the grant's schema |\n| container | No | CosmosDB container (required for CosmosDB). An access grant applies only when this equals the grant's container |\n| limit | No | Max rows (default: 100, max: 1000) |\n\n**Examples:**\nquery_database(database=\"employee_db\", statement=\"SELECT * FROM users LIMIT 10\")\nquery_database(database=\"employee\", instance=\"prod-pg\", statement=\"SELECT count(*) FROM orders\")\nquery_database(database=\"employee\", instance=\"projects/hr/instances/prod-pg\", statement=\"SELECT count(*) FROM orders\")\n\n**Notes:**\n- Masked data: masking replaces a value fully (by default \"******\"), partly (e.g. \"**rn**\"), or with a hash. maskedColumns in the result names each masked column and why (not reported for MongoDB, CosmosDB or Elasticsearch). A masked value is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing \"******\" is refused. When showing a partly masked value, wrap it in backticks: \"**rn**\" renders as bold Markdown.\n- Seeing masked values: the user can ask a project owner for a masking exemption, or, if the project allows just-in-time access, request an access grant with Unmask for this exact statement, schema and container. In a Read-write session, file the request with call_api(operationId=\"AccessGrantService/CreateAccessGrant\"); otherwise the user requests it in the SQL Editor. Once it is approved, find the grant among the user's access grants, then rerun the granted statement unchanged with the grant's schema and container. appliedAccessGrant in the result names the grant that applied.\n", + "description": "Execute a SQL query against a Bytebase database. Resolves the database by name automatically.\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| database | Yes | Database name or substring (e.g., \"employee_db\" or \"employee\") |\n| statement | Yes | SQL query to execute |\n| instance | No | Workspace instance ID/name, or the full canonical name for a project instance |\n| project | No | Project name or ID to narrow resolution |\n| schema | No | Default schema for unqualified names (Postgres search path). An access grant applies only when this equals the grant's schema |\n| container | No | CosmosDB container (required for CosmosDB). An access grant applies only when this equals the grant's container |\n| limit | No | Max rows (default: 100, max: 1000) |\n| issueTitle | No | For a statement that may write: the issue's title if the user chooses Create an issue. The form shows it in that choice. Say what the change does, without data values. Without it, the form does not offer Create an issue |\n\n**Examples:**\nquery_database(database=\"employee_db\", statement=\"SELECT * FROM users LIMIT 10\")\nquery_database(database=\"employee\", instance=\"prod-pg\", statement=\"SELECT count(*) FROM orders\")\nquery_database(database=\"employee\", instance=\"projects/hr/instances/prod-pg\", statement=\"SELECT count(*) FROM orders\")\nquery_database(database=\"employee_db\", statement=\"UPDATE employee SET active = false WHERE id = 42\", issueTitle=\"Deactivate an employee\")\n\n**Notes:**\n- Show the user the statement each answer came from, so they can check it read what they asked about.\n- When the user asks for an issue or a review of a change, call propose_database_change instead. It takes no schema, so when the request named one, qualify each name with it.\n- Masked data: masking replaces a value fully (by default \"******\"), partly (e.g. \"**rn**\"), or with a hash. maskedColumns in the result names each masked column and why (not reported for MongoDB, CosmosDB or Elasticsearch). A masked value is a placeholder, not a value anything holds, so never write it back and never filter on it. Any statement containing \"******\" is refused. When showing a partly masked value, wrap it in backticks: \"**rn**\" renders as bold Markdown.\n- Seeing masked values: the user can ask a project owner for a masking exemption, or, if the project allows just-in-time access, request an access grant with Unmask for this exact statement, schema and container. In a Read-write session, file the request with request_access_grant; otherwise the user requests it in the SQL Editor. Once it is approved, find the grant among the user's access grants, then rerun the granted statement unchanged with the grant's schema and container. appliedAccessGrant in the result names the grant that applied.\n", "inputSchema": { "type": "object", "properties": { @@ -195,6 +245,9 @@ "container": { "type": "string" }, + "issueTitle": { + "type": "string" + }, "limit": { "type": "integer" } @@ -214,6 +267,51 @@ "additionalProperties": false } }, + { + "name": "request_access_grant", + "description": "Request an access grant: time-boxed permission to run one read-only statement on one Bytebase database, optionally with results unmasked or exported. A person approves the request in Bytebase before it takes effect.\n\n| Parameter | Required | Description |\n|---------------|----------|-------------|\n| database | Yes | Full database name, as query_database prints it after \"Database:\", e.g. \"projects/hr/instances/prod/databases/hr\" |\n| statement | Yes | One read-only statement; the grant applies to this exact statement |\n| schema | No | Default schema for unqualified names; the rerun must pass the same one |\n| container | No | CosmosDB container; the rerun must pass the same one |\n| unmask | No | true to return masked columns unmasked |\n| export | No | true to allow exporting the results |\n| reason | Yes | Why the access is needed; the approver reads it |\n| durationHours | Yes | Hours of access, counted from approval. The SQL Editor offers 1, 4, 24 and 168; the workspace maximum applies |\n\nThe project must allow just-in-time access. Check allowJustInTimeAccess with call_api(operationId=\"ProjectService/GetProject\") first; a missing field means off, and set_just_in_time_access turns it on.\n\nClients such as Claude Code ask the user to approve each call of this tool, so do not ask in chat first. Once the request is approved, rerun the statement unchanged with query_database, with the same schema and container; appliedAccessGrant in its result names the grant that applied. To use an export grant, pass the statement the same way to call_api(operationId=\"SQLService/Export\"); query_database returns at most 1000 rows.", + "inputSchema": { + "type": "object", + "properties": { + "database": { + "type": "string" + }, + "statement": { + "type": "string" + }, + "schema": { + "type": "string" + }, + "container": { + "type": "string" + }, + "unmask": { + "type": "boolean" + }, + "export": { + "type": "boolean" + }, + "reason": { + "type": "string" + }, + "durationHours": { + "type": "integer", + "minimum": -2147483648, + "maximum": 2147483647 + } + }, + "required": [ + "database", + "statement", + "reason", + "durationHours" + ], + "additionalProperties": false + }, + "_meta": { + "anthropic/requiresUserInteraction": true + } + }, { "name": "revoke_masking_exemption", "description": "Remove one member's masking exemption in a Bytebase project. The user confirms in this client first.\n\n| Parameter | Required | Description |\n|-----------|----------|-------------|\n| project | Yes | Project name, e.g. \"projects/hr\" |\n| member | Yes | The member as the policy lists it, e.g. \"user:bob@example.com\" |\n| condition | Yes | The exemption's condition expression, exactly as OrgPolicyService/GetPolicy returns it for \"{project}/policies/masking_exemption\"; \"\" for an exemption with no condition |\n\nThe member is removed from every exemption whose condition matches exactly; an exemption left with no member is removed. Other members and other exemptions stay as they are. The tool asks the user to confirm in a form, and writes only when they accept. A client that cannot show the form gets the project's masking exemption page.\n\nThe same permissions apply as in the console.", @@ -240,7 +338,7 @@ }, { "name": "search_api", - "description": "Discover Bytebase API endpoints. **Always call before call_api - never guess schemas.**\n\n| Mode | Parameters | Result |\n|------|------------|--------|\n| List | (none) | All services |\n| Browse | service=\"SQLService\" | All endpoints in service |\n| Details | operationId=\"SQLService/Query\" | Request/response schema |\n| Schema | schema=\"Instance\" | Message type definition |\n\n**Workflow:** search_api() → search_api(service=\"...\") → search_api(operationId=\"...\") → call_api(...)", + "description": "Discover Bytebase API endpoints. **Always call before call_api - never guess schemas.**\n\n| Mode | Parameters | Result |\n|------|------------|--------|\n| List | (none) | All services |\n| Browse | service=\"SQLService\" | All endpoints in service |\n| Details | operationId=\"SQLService/Query\" | Request/response schema |\n| Schema | schema=\"Instance\" | Message type definition |\n\n**Workflow:** search_api() → search_api(service=\"...\") → search_api(operationId=\"...\") → call_api(...)\n\nThe results also name what no MCP session can do, whatever the workspace's MCP mode and the user's permissions, and why: those are done in the Bytebase console.", "inputSchema": { "type": "object", "properties": { diff --git a/src/upstream.ts b/src/upstream.ts index 4e583e3..db55636 100644 --- a/src/upstream.ts +++ b/src/upstream.ts @@ -11,165 +11,263 @@ import { type ClientCapabilities, type ElicitRequest, type ElicitResult, + type Implementation, type ListToolsResult, } from "@modelcontextprotocol/sdk/types.js"; -import { FileOAuthClientProvider } from "./auth.js"; +import { FileOAuthClientProvider, SignInRequiredError, clientIdentity, signInPermitted, type SignInPermit } from "./auth.js"; import { mcpEndpoint, type Config } from "./config.js"; import { log } from "./log.js"; -import { PACKAGE_VERSION } from "./version.js"; + +/** + * The proxy adds no deadline to a forwarded request, in either direction + * (docs/DESIGN.md, D5); the SDK would otherwise give each one 60 seconds. + */ +export const NO_TIMEOUT_MS = 2 ** 31 - 1; export interface UpstreamHooks { - /** Capabilities to declare to Bytebase: the ones the downstream client declared to us. */ + /** Capabilities to declare to Bytebase: the elicitation the downstream client declared. */ clientCapabilities: () => ClientCapabilities; - /** Forward an elicitation (confirmation form) from Bytebase to the downstream client. */ - onElicit?: (params: ElicitRequest["params"]) => Promise; + /** + * Forward an elicitation (confirmation form) from Bytebase to the downstream + * client; `signal` aborts when Bytebase withdraws it. + */ + onElicit?: (params: ElicitRequest["params"], signal: AbortSignal) => Promise; /** Bytebase changed its tool list. */ onToolListChanged?: () => void; } +export interface OpenOptions { + /** Whether a browser sign-in may start. */ + interactive: boolean; + /** Whether to wait for another holder of the sign-in's lock. */ + waitForLock: boolean; +} + /** - * One connection to a Bytebase instance's /mcp endpoint, opened lazily and - * re-opened after it drops. Sign-in runs through {@link FileOAuthClientProvider}. + * One connection to a Bytebase instance's /mcp endpoint for one client + * application, opened under the sign-in's lock (docs/DESIGN.md, D7). */ export class Upstream { private readonly endpoint: URL; - private readonly provider: FileOAuthClientProvider; + readonly provider: FileOAuthClientProvider; private client?: Client; + private readonly inFlight = new WeakMap(); + private readonly retiring = new Set(); private connecting?: Promise; + private connectingInteractive = false; - constructor(private readonly config: Config & { url: URL }, private readonly hooks: UpstreamHooks) { + constructor( + private readonly config: Config & { url: URL }, + private readonly clientInfo: Implementation | undefined, + private readonly hooks: UpstreamHooks, + ) { this.endpoint = mcpEndpoint(config.url); - this.provider = new FileOAuthClientProvider(config.url, { + this.provider = new FileOAuthClientProvider(config.url, clientIdentity(clientInfo), { home: config.home, callbackPort: config.callbackPort, openBrowser: config.openBrowser, }); } - get tokenFile(): string { - return this.provider.tokenFile; + /** The open session, if any. */ + get session(): Client | undefined { + return this.client; } - /** Returns the connected client, signing in and connecting when needed. */ - async get(): Promise { + /** Whether an opening that may sign in in the browser is in progress. */ + get signingIn(): boolean { + return Boolean(this.connecting) && this.connectingInteractive; + } + + /** Returns the session, opening it under the sign-in's lock when needed. */ + async open(options: OpenOptions): Promise { if (this.client) return this.client; + // An opening that may not sign in (initialize's) is waited out, then a sign-in + // starts if it did not open the session. + if (this.connecting && options.interactive && !this.connectingInteractive) { + await this.connecting.catch(() => undefined); + if (this.client) return this.client; + } if (!this.connecting) { - this.connecting = this.connect().finally(() => { + this.connectingInteractive = options.interactive; + this.connecting = this.openLocked(options).finally(() => { this.connecting = undefined; }); } return this.connecting; } - /** Forgets the current session so the next call reconnects. */ + /** Closes the current session at once; for shutdown. */ reset(): void { const client = this.client; this.client = undefined; void client?.close().catch(() => undefined); } - /** Forgets the stored sign-in for this instance. */ - signOut(): void { - this.reset(); - this.provider.clear(); + /** + * Stops sending to the current session so the next request reconnects. Calls + * already in flight on it may have run on the instance, so it closes only once + * the last of them settles and they still return their results. + */ + private retire(client: Client): void { + if (this.client === client) this.client = undefined; + if ((this.inFlight.get(client) ?? 0) === 0) void client.close().catch(() => undefined); + else this.retiring.add(client); } - async listTools(): Promise { - return this.withRetry((client) => client.request({ method: "tools/list", params: {} }, ListToolsResultSchema)); + /** Counts a request on its session, closing a retired session after its last one. */ + private async track(client: Client, request: Promise): Promise { + this.inFlight.set(client, (this.inFlight.get(client) ?? 0) + 1); + try { + return await request; + } finally { + const left = (this.inFlight.get(client) ?? 1) - 1; + this.inFlight.set(client, left); + if (left === 0 && this.retiring.delete(client)) void client.close().catch(() => undefined); + } } - async callTool(params: CallToolRequest["params"]): Promise { - // Raw request rather than client.callTool(): the latter validates - // structuredContent against a tool list it may not have fetched, and this - // package passes results through untouched. - return this.withRetry((client) => client.request({ method: "tools/call", params }, CallToolResultSchema)); + /** + * Lists one page of the session's tools; the client's cursor goes to the + * instance as is. After an error showing the instance never received the + * request, such as a session it ended, it reopens with the stored sign-in and + * asks once more. + */ + async listTools(cursor?: string, signal?: AbortSignal): Promise { + let used: Client | undefined; + const send = async () => { + const client = (used = await this.open({ interactive: false, waitForLock: true })); + // A caller that gave up while the session reopened does not send the request. + signal?.throwIfAborted(); + return this.track(client, client.request({ method: "tools/list", params: cursor ? { cursor } : {} }, ListToolsResultSchema, { signal })); + }; + try { + return await send(); + } catch (err) { + if (signal?.aborted || !neverReceived(err)) throw err; + log(`the instance did not receive tools/list (${describe(err)}); reconnecting`); + // Retire the session the request failed on, not one another call already reopened. + if (used) this.retire(used); + return send(); + } } - /** Runs fn once; if the session dropped underneath it, reconnects and runs it once more. */ - private async withRetry(fn: (client: Client) => Promise): Promise { - const client = await this.get(); + /** + * Forwards a tool call. It follows the client: a call cancelled before its + * session opens is never sent, and it is resent only after an error showing + * the instance never received it. + */ + async callTool(params: CallToolRequest["params"], signal?: AbortSignal): Promise { + let used: Client | undefined; + const send = async () => { + const client = (used = await this.open({ interactive: true, waitForLock: true })); + signal?.throwIfAborted(); + // Raw request rather than client.callTool(): that validates structuredContent + // against a tool list it may not have, and results pass through untouched. + return this.track(client, client.request({ method: "tools/call", params }, CallToolResultSchema, { signal, timeout: NO_TIMEOUT_MS })); + }; try { - return await fn(client); + return await send(); } catch (err) { - if (!isConnectionLoss(err)) throw err; - log(`connection to ${this.endpoint} dropped (${describe(err)}); reconnecting`); - this.reset(); - return fn(await this.get()); + if (signal?.aborted || !neverReceived(err)) throw err; + log(`the instance did not receive the call (${describe(err)}); reconnecting`); + // Retire the session the request failed on, not one another call already reopened. + if (used) this.retire(used); + return send(); } } - private async connect(): Promise { + private async openLocked(options: OpenOptions): Promise { + const held = await this.provider.withLock(() => this.connect(options.interactive), { wait: options.waitForLock }); + if (!held) throw new SignInRequiredError("another process holds this sign-in"); + return held.value; + } + + private async connect(interactive: boolean): Promise { + const permit: SignInPermit = { active: interactive }; + try { + return await signInPermitted.run(permit, () => this.attemptConnect(interactive)); + } catch (err) { + if (permit.browserOpened && typeof err === "object" && err !== null) failedAfterBrowser.add(err); + throw err; + } finally { + permit.active = false; + } + } + + private async attemptConnect(interactive: boolean): Promise { const capabilities = this.hooks.clientCapabilities(); const forwardsElicitation = Boolean(capabilities.elicitation) && Boolean(this.hooks.onElicit); - - for (let attempt = 1; ; attempt++) { - const transport = new StreamableHTTPClientTransport(this.endpoint, { authProvider: this.provider }); - const client = new Client( - { name: "bytebase-mcp", title: "Bytebase MCP (npm)", version: PACKAGE_VERSION }, - { - capabilities: { - ...(forwardsElicitation ? { elicitation: capabilities.elicitation } : {}), - }, - }, - ); - if (forwardsElicitation) { - client.setRequestHandler(ElicitRequestSchema, async (request) => this.hooks.onElicit!(request.params)); - } - client.setNotificationHandler(ToolListChangedNotificationSchema, () => { - this.hooks.onToolListChanged?.(); - }); - client.onclose = () => { - if (this.client === client) this.client = undefined; - }; - client.onerror = (err) => { - // Closing a session aborts its SSE stream; that is not an error worth a line. - if (/AbortError|operation was aborted/.test(describe(err))) return; - log(`upstream error: ${describe(err)}`); - }; - - try { - await client.connect(transport); - this.client = client; - return client; - } catch (err) { - if (err instanceof UnauthorizedError && attempt === 1) { - const code = await this.provider.waitForAuthorizationCode(); - await transport.finishAuth(code); - log("signed in; connecting"); - continue; + { + for (let attempt = 1; ; attempt++) { + const transport = new StreamableHTTPClientTransport(this.endpoint, { authProvider: this.provider, fetch: this.provider.fetch }); + const client = new Client(this.clientInfo ?? { name: "bytebase-mcp", version: "0" }, { + capabilities: forwardsElicitation ? { elicitation: capabilities.elicitation } : {}, + }); + if (forwardsElicitation) { + client.setRequestHandler(ElicitRequestSchema, async (request, extra) => this.hooks.onElicit!(request.params, extra.signal)); + } + client.setNotificationHandler(ToolListChangedNotificationSchema, () => this.hooks.onToolListChanged?.()); + client.onclose = () => { + if (this.client === client) this.client = undefined; + }; + client.onerror = (err) => { + if (/AbortError|operation was aborted/.test(describe(err))) return; + log(`upstream error: ${describe(err)}`); + }; + try { + await client.connect(transport); + this.client = client; + return client; + } catch (err) { + if (findSignInRequired(err)) throw findSignInRequired(err); + if (err instanceof UnauthorizedError && interactive && attempt === 1) { + const code = await this.provider.waitForAuthorizationCode(); + await transport.finishAuth(code); + log("signed in; connecting"); + continue; + } + throw new Error(`cannot connect to ${this.endpoint}: ${describe(err)}${hint(err)}`, { cause: err }); } - throw new Error(`cannot connect to ${this.endpoint}: ${describe(err)}${hint(err)}`, { cause: err }); } } } } -function isConnectionLoss(err: unknown): boolean { +function findSignInRequired(err: unknown): SignInRequiredError | undefined { + for (let e: unknown = err; e; e = (e as { cause?: unknown }).cause) { + if (e instanceof SignInRequiredError) return e; + } + return undefined; +} + +/** + * Errors that show the instance never received the request. A refused sign-in + * in an open session counts: Bytebase answered 401 (a revoked grant, as after + * reauthorize), so the request did not run. + */ +function neverReceived(err: unknown): boolean { + if (findSignInRequired(err)) return true; const text = describe(err).toLowerCase(); - return ( - text.includes("not connected") || - text.includes("session not found") || - text.includes("econnreset") || - text.includes("econnrefused") || - text.includes("fetch failed") || - text.includes("terminated") || - text.includes("http 404") || - text.includes("http 401") - ); + return text.includes("econnrefused") || text.includes("session not found") || text.includes("http 404") || text.includes("http 401") || text.includes("not connected"); } -/** A next step for the errors users hit most. */ function hint(err: unknown): string { const text = describe(err); if (/Protected resource .* does not match/i.test(text)) { return ". BYTEBASE_URL must be the instance's external URL (Settings > General > External URL), because Bytebase binds MCP tokens to it"; } - if (/sign-in timed out/i.test(text)) { - return ". Run `bytebase-mcp login` to sign in again"; - } + if (/sign-in timed out/i.test(text)) return ". Call a tool again to restart the sign-in"; return ""; } +const failedAfterBrowser = new WeakSet(); + +/** Whether an opening failed after its browser sign-in started, so it is not retried (docs/DESIGN.md, D5). */ +export function isFailedSignIn(err: unknown): boolean { + return typeof err === "object" && err !== null && failedAfterBrowser.has(err); +} + export function describe(err: unknown): string { if (err instanceof Error) { const cause = (err as Error & { cause?: unknown }).cause; diff --git a/test/browser.test.mjs b/test/browser.test.mjs new file mode 100644 index 0000000..4b1a549 --- /dev/null +++ b/test/browser.test.mjs @@ -0,0 +1,26 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { browserCommand } from "../dist/browser.js"; + +const url = "https://bb.example.com/api/oauth2/authorize?client_id=a&state=b|c^d%25e"; + +test("browserCommand opens http(s) sign-in URLs with each platform's opener", () => { + assert.deepEqual(browserCommand(url, "darwin"), { command: "open", args: [url] }); + assert.deepEqual(browserCommand(url, "linux"), { command: "xdg-open", args: [url] }); + assert.deepEqual(browserCommand("http://localhost:8080/api/oauth2/authorize?x=1", "linux"), { + command: "xdg-open", + args: ["http://localhost:8080/api/oauth2/authorize?x=1"], + }); +}); + +test("browserCommand on Windows passes the URL to rundll32 untouched, never through cmd", () => { + assert.deepEqual(browserCommand(url, "win32"), { command: "rundll32", args: ["url.dll,FileProtocolHandler", url] }); +}); + +test("browserCommand opens nothing that is not http(s)", () => { + for (const other of ["file:///etc/passwd", "ms-settings:", "vscode://x/y", "ftp://bb.example.com/", "not a url"]) { + for (const platform of ["darwin", "linux", "win32"]) { + assert.equal(browserCommand(other, platform), undefined, `${other} on ${platform}`); + } + } +}); diff --git a/test/config.test.mjs b/test/config.test.mjs index e0bd70d..249596a 100644 --- a/test/config.test.mjs +++ b/test/config.test.mjs @@ -20,3 +20,16 @@ test("loadConfig reads the environment", () => { assert.equal(loadConfig({}).openBrowser, true); assert.throws(() => loadConfig({ BYTEBASE_MCP_CALLBACK_PORT: "abc" })); }); + +test("startupRetryDelaysMs: ten waits, doubling from 1s to a 5-minute ceiling, about 14 minutes in all", async () => { + const { startupRetryDelaysMs } = await import("../dist/retry.js"); + assert.deepEqual(startupRetryDelaysMs(), [1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, 256000, 300000]); +}); + +test("loadConfig keeps sign-ins in ~/.bytebase-mcp, not under XDG config", async () => { + const os = await import("node:os"); + const path = await import("node:path"); + assert.equal(loadConfig({}).home, path.join(os.homedir(), ".bytebase-mcp")); + assert.equal(loadConfig({ XDG_CONFIG_HOME: "/tmp/xdg" }).home, path.join(os.homedir(), ".bytebase-mcp")); + assert.equal(loadConfig({ BYTEBASE_MCP_HOME: "/tmp/elsewhere" }).home, "/tmp/elsewhere"); +}); diff --git a/test/fake-upstream.mjs b/test/fake-upstream.mjs new file mode 100644 index 0000000..f6ad128 --- /dev/null +++ b/test/fake-upstream.mjs @@ -0,0 +1,300 @@ +// A fake Bytebase for tests: the protected-resource document, +// an OAuth server (registration, a browser leg that redirects at once, single-use +// refresh tokens) and an MCP endpoint that requires its tokens. It records what +// the proxy sent. +import http from "node:http"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { ElicitResultSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { createHash, randomUUID } from "node:crypto"; + +/** The tools the fake's MCP endpoint serves. */ +export const FAKE_TOOLS = { + tools: [ + { name: "query_database", description: "Run a query.", inputSchema: { type: "object", properties: {} } }, + { name: "get_schema", description: "Read a schema.", inputSchema: { type: "object", properties: {} } }, + ], +}; + +/** What the fake's MCP endpoint says at initialize, as Bytebase does: an account line first. */ +export const SESSION_INSTRUCTIONS = "In workspaces/ws-fake, this session acts as the Bytebase account dev@example.com.\n\nFake session instructions."; + +/** + * Starts the fake. Without `resourceMetadata` it answers like a server that is + * not Bytebase. `pageSize` makes tools/list page; `port` fixes the port. + */ +export async function startFakeBytebase({ resourceMetadata = true, pageSize = 0, port = 0, streamed = false, reauthorizeTool = false } = {}) { + const sessions = new Map(); + const eventStreams = new Set(); + const requests = []; + const state = { resourceMetadata, refreshDelayMs: 0, listDelayMs: 0, callDelayMs: 0, revokeStalls: false, withdrawFormAfterMs: 0, gatewayStatus: 0, gatewayPath: "" }; + const registrations = []; + const initializes = []; + const toolCalls = []; + const toolLists = []; + const revocations = []; + let refreshes = 0; + let counter = 0; + const codes = new Map(); + const accessTokens = new Set(); + const refreshTokens = new Set(); + + const issue = () => { + const access = `at-${++counter}`; + const refresh = `rt-${counter}`; + accessTokens.add(access); + refreshTokens.add(refresh); + return { access_token: access, refresh_token: refresh, token_type: "Bearer", expires_in: 3600 }; + }; + const json = (res, status, body) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body)); + const readBody = (req) => + new Promise((resolve) => { + let data = ""; + req.on("data", (chunk) => (data += chunk)); + req.on("end", () => resolve(data)); + }); + + const server = http.createServer(async (req, res) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + requests.push(`${req.method} ${url.pathname}`); + if (state.gatewayStatus && url.pathname.startsWith(state.gatewayPath)) { + res.writeHead(state.gatewayStatus, { "Content-Type": "text/html" }).end("Bad Gateway"); + return; + } + + if (req.method === "GET" && url.pathname === "/.well-known/oauth-protected-resource/mcp" && state.resourceMetadata) { + json(res, 200, { resource: `${base}/mcp`, authorization_servers: [base] }); + return; + } + if (req.method === "GET" && url.pathname === "/.well-known/oauth-authorization-server") { + json(res, 200, { + issuer: base, + authorization_endpoint: `${base}/authorize`, + token_endpoint: `${base}/token`, + registration_endpoint: `${base}/register`, + revocation_endpoint: `${base}/revoke`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + }); + return; + } + if (req.method === "POST" && url.pathname === "/register") { + const body = JSON.parse(await readBody(req)); + registrations.push(body); + json(res, 201, { ...body, client_id: `client-${registrations.length}` }); + return; + } + if (req.method === "GET" && url.pathname === "/authorize") { + const code = `code-${++counter}`; + codes.set(code, url.searchParams.get("code_challenge")); + const redirect = new URL(url.searchParams.get("redirect_uri")); + redirect.searchParams.set("code", code); + redirect.searchParams.set("state", url.searchParams.get("state") ?? ""); + res.writeHead(302, { Location: redirect.toString() }).end(); + return; + } + if (req.method === "POST" && url.pathname === "/revoke" && state.revokeStalls) { + return; // accepts the connection and never answers + } + if (req.method === "POST" && url.pathname === "/revoke") { + const form = new URLSearchParams(await readBody(req)); + revocations.push({ token: form.get("token"), clientId: form.get("client_id") }); + refreshTokens.delete(form.get("token")); + res.writeHead(200).end(); + return; + } + if (req.method === "POST" && url.pathname === "/token") { + const form = new URLSearchParams(await readBody(req)); + if (form.get("grant_type") === "authorization_code" && codes.has(form.get("code"))) { + // PKCE, as Bytebase checks it: the verifier must hash to the challenge sent at authorize. + const challenge = codes.get(form.get("code")); + codes.delete(form.get("code")); + const verifier = form.get("code_verifier") ?? ""; + if (createHash("sha256").update(verifier).digest("base64url") !== challenge) { + json(res, 400, { error: "invalid_grant", error_description: "PKCE verification failed" }); + return; + } + json(res, 200, issue()); + } else if (form.get("grant_type") === "refresh_token") { + refreshes++; + if (state.refreshDelayMs > 0) await new Promise((resolve) => setTimeout(resolve, state.refreshDelayMs)); + if (refreshTokens.delete(form.get("refresh_token"))) json(res, 200, issue()); + else json(res, 400, { error: "invalid_grant", error_description: "refresh token reused" }); + } else { + json(res, 400, { error: "invalid_grant" }); + } + return; + } + if (url.pathname === "/mcp") { + const bearer = (req.headers.authorization ?? "").replace(/^Bearer /, ""); + if (!accessTokens.has(bearer)) { + res + .writeHead(401, { "WWW-Authenticate": `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource/mcp"` }) + .end(); + return; + } + const raw = req.method === "POST" ? await readBody(req) : ""; + const body = raw ? JSON.parse(raw) : undefined; + for (const message of Array.isArray(body) ? body : body ? [body] : []) { + if (message.method === "initialize") initializes.push(message.params); + if (message.method === "tools/call") { + toolCalls.push(message.params); + if (state.callDelayMs > 0) await new Promise((resolve) => setTimeout(resolve, state.callDelayMs)); + } + if (message.method === "tools/list") { + toolLists.push(message.params); + if (state.listDelayMs > 0) await new Promise((resolve) => setTimeout(resolve, state.listDelayMs)); + } + } + const sessionId = req.headers["mcp-session-id"]; + if (sessionId) { + const transport = sessions.get(sessionId); + if (!transport) { + json(res, 404, { jsonrpc: "2.0", id: null, error: { code: -32001, message: "Session not found" } }); + return; + } + if (req.method === "GET") { + eventStreams.add(res); + res.on("close", () => eventStreams.delete(res)); + } + await transport.handleRequest(req, res, body); + return; + } + const mcp = new McpServer({ name: "fake-bytebase", version: "0.0.0" }, { instructions: SESSION_INSTRUCTIONS }); + // Bytebase's Go SDK numbers its requests from 1 (jsonrpc2 conn.go); this SDK starts at 0. + mcp.server._requestMessageId = 1; + for (const tool of FAKE_TOOLS.tools) { + mcp.registerTool(tool.name, { description: tool.description }, async () => ({ content: [{ type: "text", text: `ran ${tool.name}` }] })); + } + // Asks for confirmation with a form, as Bytebase's decide_issue does, and + // waits up to Bytebase's confirmationLifetime (10 minutes) for the answer. + // Bytebase's account-switch tool: revokes the grant and says to retry or reconnect. + if (reauthorizeTool) mcp.registerTool("reauthorize", { description: "Log out the current MCP OAuth connection." }, async () => { + accessTokens.clear(); + refreshTokens.clear(); + return { content: [{ type: "text", text: "OAuth refresh grant revoked. Retry or reconnect this MCP server to run OAuth again." }] }; + }); + if (streamed) mcp.registerTool("confirm_change", { description: "Asks the user to confirm." }, async (extra) => { + const withdraw = new AbortController(); + if (state.withdrawFormAfterMs > 0) setTimeout(() => withdraw.abort(), state.withdrawFormAfterMs); + try { + // Sent within the call, so the form and its withdrawal travel on the call's stream. + const answer = await extra.sendRequest( + { method: "elicitation/create", params: { mode: "form", message: "Approve the change?", requestedSchema: { type: "object", properties: {} } } }, + ElicitResultSchema, + { timeout: 10 * 60 * 1000, signal: withdraw.signal }, + ); + return { content: [{ type: "text", text: `form ${answer.action}` }] }; + } catch (err) { + // The SDK sends the cancellation without waiting; let it leave before the result + // closes the call's stream, as Bytebase's arrives on a stream of its own. + await new Promise((resolve) => setTimeout(resolve, 200)); + return { content: [{ type: "text", text: `form withdrawn (${err.message})` }] }; + } + }); + if (pageSize > 0) { + // Pages the list like a server with a small page size; the cursor is an offset. + mcp.server.setRequestHandler(ListToolsRequestSchema, async (request) => { + const offset = Number(request.params?.cursor ?? 0); + const tools = FAKE_TOOLS.tools.slice(offset, offset + pageSize).map((tool) => ({ ...tool })); + const next = offset + pageSize; + return next < FAKE_TOOLS.tools.length ? { tools, nextCursor: String(next) } : { tools }; + }); + } + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + // A form is a request sent to the client during a call, so form tests stream responses. + enableJsonResponse: !streamed, + onsessioninitialized: (id) => sessions.set(id, transport), + }); + transport.onclose = () => { + if (transport.sessionId) sessions.delete(transport.sessionId); + }; + await mcp.connect(transport); + await transport.handleRequest(req, res, body); + return; + } + res.writeHead(404).end(); + }); + await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + return { + url: base, + requests, + registrations, + initializes, + toolCalls, + toolLists, + revocations, + get refreshes() { + return refreshes; + }, + /** Revokes every access token, so the next MCP request needs a refresh. */ + expireAccessTokens() { + accessTokens.clear(); + }, + /** Stops listening, like an outage: connections are refused; tokens survive. */ + goDown() { + server.closeAllConnections?.(); + return new Promise((resolve) => server.close(resolve)); + }, + /** Listens again on the same port after goDown. */ + comeBack() { + return new Promise((resolve) => server.listen(Number(new URL(base).port), "127.0.0.1", resolve)); + }, + /** Forgets every MCP session, as Bytebase does after an hour idle. */ + expireSessions() { + sessions.clear(); + }, + /** Revokes every token, so the next MCP request needs a new sign-in. */ + revokeAllTokens() { + accessTokens.clear(); + refreshTokens.clear(); + // Open event streams end, as they would on a revoked grant, so clients reconnect them. + for (const res of eventStreams) res.end(); + }, + /** Delays answers to tools/call, as a long-running tool would. */ + set callDelayMs(ms) { + state.callDelayMs = ms; + }, + /** Withdraws each confirmation form this long after sending it, as Bytebase can. */ + set withdrawFormAfterMs(ms) { + state.withdrawFormAfterMs = ms; + }, + /** Answers every request with this status, as a reverse proxy does while Bytebase is down; 0 stops. */ + set gatewayStatus(status) { + state.gatewayStatus = status; + }, + /** Limits gatewayStatus to paths starting with this prefix; "" means every path. */ + set gatewayPath(prefix) { + state.gatewayPath = prefix; + }, + /** Makes the revocation endpoint accept requests and never answer. */ + set revokeStalls(value) { + state.revokeStalls = value; + }, + /** Delays answers to tools/list, as a slow instance would. */ + set listDelayMs(ms) { + state.listDelayMs = ms; + }, + /** Delays answers to refresh requests, as a slow instance would. */ + set refreshDelayMs(ms) { + state.refreshDelayMs = ms; + }, + close: () => { + server.closeAllConnections?.(); + return new Promise((resolve) => server.close(resolve)); + }, + }; +} + +/** Plays the browser: follows a sign-in URL to the proxy's loopback callback. */ +export async function completeSignIn(authorizationUrl) { + const first = await fetch(authorizationUrl, { redirect: "manual" }); + const callback = first.headers.get("location"); + if (!callback) throw new Error(`authorize did not redirect (HTTP ${first.status})`); + const done = await fetch(callback); + if (!done.ok) throw new Error(`callback answered HTTP ${done.status}`); +} diff --git a/test/sessions.test.mjs b/test/sessions.test.mjs new file mode 100644 index 0000000..483dcd5 --- /dev/null +++ b/test/sessions.test.mjs @@ -0,0 +1,603 @@ +// Sessions, sign-in and the token lock (docs/DESIGN.md D5–D7, D9, S3, S4), +// driven over stdio against a fake Bytebase. The test plays the browser by +// following the sign-in URL the proxy prints. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ElicitRequestSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; +import { completeSignIn, startFakeBytebase, SESSION_INSTRUCTIONS } from "./fake-upstream.mjs"; + +const entry = path.join(import.meta.dirname, "..", "dist", "index.js"); +let nextPort = 52100 + Math.floor(Math.random() * 500); + +function freshHome() { + return fs.mkdtempSync(path.join(os.tmpdir(), "bytebase-mcp-test-")); +} + +/** Starts a proxy as `clientName` and collects the sign-in URLs it prints. */ +async function connect({ url, home, port, clientName = "sessions-client", title, onForm }) { + // Anything not given is a fresh client of a fresh fake instance. + const transport = new StdioClientTransport({ + command: process.execPath, + args: [entry], + env: { + ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("BYTEBASE_"))), + BYTEBASE_URL: url, + BYTEBASE_MCP_HOME: home, + BYTEBASE_MCP_CALLBACK_PORT: String(port), + BYTEBASE_MCP_NO_BROWSER: "1", + }, + stderr: "pipe", + }); + const signIns = []; + const waiters = []; + const client = new Client({ name: clientName, title, version: "1.2.3" }, { capabilities: onForm ? { elicitation: { form: {} } } : {} }); + if (onForm) client.setRequestHandler(ElicitRequestSchema, (request, extra) => onForm(request.params, extra)); + const started = client.connect(transport); + transport.stderr.setEncoding("utf8"); + transport.stderr.on("data", (text) => { + for (const match of text.matchAll(/https?:\/\/\S+\/authorize\?\S+/g)) { + const waiter = waiters.shift(); + if (waiter) waiter(match[0]); + else signIns.push(match[0]); + } + }); + await started; + return { + client, + signIns, + /** Resolves with the next sign-in URL the proxy prints. */ + nextSignIn: () => (signIns.length > 0 ? Promise.resolve(signIns.shift()) : new Promise((resolve) => waiters.push(resolve))), + }; +} + +test("D5/D6: the first tool call signs in as the real client, then runs", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++, title: "Sessions Client" }); + t.after(() => proxy.client.close()); + + const call = proxy.client.callTool({ name: "query_database", arguments: {} }); + await completeSignIn(await proxy.nextSignIn()); + const result = await call; + assert.equal(result.content[0].text, "ran query_database"); + + assert.deepEqual( + bytebase.registrations.map((r) => r.client_name), + ["Sessions Client via Bytebase MCP"], + ); + assert.equal(bytebase.initializes.at(-1).clientInfo.name, "sessions-client", "the client's own clientInfo reaches the instance"); +}); + +/** 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 }); + const call = proxy.client.callTool({ name: "get_schema", arguments: {} }); + await completeSignIn(await proxy.nextSignIn()); + await call; + await proxy.client.close(); +} + +test("S2: a stored sign-in opens the session at initialize and passes its instructions through", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal(proxy.client.getInstructions(), SESSION_INSTRUCTIONS, "the instance's own text, account line included"); + const result = await proxy.client.callTool({ name: "query_database", arguments: {} }); + assert.equal(result.content[0].text, "ran query_database"); + assert.equal(bytebase.registrations.length, 1, "the stored registration is reused"); + assert.equal(proxy.signIns.length, 0); +}); + +test("D7: two processes refreshing at once send one refresh", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const first = await connect({ url: bytebase.url, home, port }); + const second = await connect({ url: bytebase.url, home, port }); + t.after(() => Promise.all([first.client.close(), second.client.close()])); + bytebase.expireAccessTokens(); + const results = await Promise.all([ + first.client.callTool({ name: "query_database", arguments: {} }), + second.client.callTool({ name: "query_database", arguments: {} }), + ]); + assert.deepEqual( + results.map((r) => r.content[0].text), + ["ran query_database", "ran query_database"], + ); + assert.equal(bytebase.refreshes, 1, "the second process used the tokens the first one saved"); +}); + +test("D7: two processes signing in for the first time register once and sign in once", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + const first = await connect({ url: bytebase.url, home, port }); + const second = await connect({ url: bytebase.url, home, port }); + t.after(() => Promise.all([first.client.close(), second.client.close()])); + + const calls = [first, second].map((proxy) => proxy.client.callTool({ name: "query_database", arguments: {} })); + const url = await Promise.race([first.nextSignIn(), second.nextSignIn()]); + await completeSignIn(url); + const results = await Promise.all(calls); + assert.deepEqual( + results.map((r) => r.content[0].text), + ["ran query_database", "ran query_database"], + ); + assert.equal(bytebase.registrations.length, 1); + 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) => { + 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, []); + + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + assert.deepEqual( + (await proxy.client.listTools()).tools.map((tool) => tool.name), + ["query_database", "get_schema"], + ); +}); + +test("D5: a call cancelled while sign-in is pending is never sent", 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 cancel = new AbortController(); + const call = proxy.client.callTool({ name: "query_database", arguments: {} }, undefined, { signal: cancel.signal }); + const url = await proxy.nextSignIn(); + cancel.abort(); + await assert.rejects(call); + await completeSignIn(url); + const later = await proxy.client.callTool({ name: "get_schema", arguments: {} }); + assert.equal(later.content[0].text, "ran get_schema"); + assert.deepEqual( + bytebase.toolCalls.map((c) => c.name), + ["get_schema"], + "the cancelled query_database never reached the instance", + ); +}); + +test("D9: status shows the stored sign-ins without signing in, and logout forgets them", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + await signInOnce(bytebase, home, nextPort++); + const run = async (command) => { + const { execFile } = await import("node:child_process"); + return new Promise((resolve, reject) => + execFile(process.execPath, [entry, command, "--url", bytebase.url], { env: { ...process.env, BYTEBASE_MCP_HOME: home } }, (err, stdout) => + err ? reject(err) : resolve(stdout), + ), + ); + }; + const status = JSON.parse(await run("status")); + assert.deepEqual(status.signIns, ["sessions-client"]); + assert.equal(status.bytebase, true); + const stored = JSON.parse(fs.readFileSync(path.join(status.signInDirectory, "sessions-client.json"), "utf8")); + await run("logout"); + assert.deepEqual(JSON.parse(await run("status")).signIns, []); + assert.deepEqual( + bytebase.revocations, + [{ token: stored.tokens.refresh_token, clientId: stored.clientInformation.client_id }], + "logout revokes the refresh token at Bytebase before deleting it", + ); +}); + +test("D5: a stored sign-in refused after the initialize bound still leads to a browser sign-in", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + bytebase.revokeAllTokens(); + bytebase.refreshDelayMs = 6000; + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.match(proxy.client.getInstructions() ?? "", /sign in/i, "initialize did not wait past its bound"); + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + assert.deepEqual( + (await proxy.client.listTools()).tools.map((tool) => tool.name), + ["query_database", "get_schema"], + ); +}); + +/** Lists every tool, following the proxy's cursors. */ +async function listAll(client) { + const names = []; + let cursor; + do { + const page = await client.listTools(cursor ? { cursor } : undefined); + names.push(...page.tools.map((tool) => tool.name)); + cursor = page.nextCursor; + } while (cursor); + return names; +} + +test("D2: the session's pages reach the client, cursors passed through", async (t) => { + const bytebase = await startFakeBytebase({ pageSize: 1 }); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + const first = await proxy.client.listTools(); + assert.equal(first.tools.length, 1, "the instance's page size, not the proxy's"); + assert.ok(first.nextCursor); + assert.deepEqual(await listAll(proxy.client), ["query_database", "get_schema"]); +}); + +test("D5: tools/list after the instance ended the session reopens it with the stored sign-in", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.listTools()).tools.length, 2); + bytebase.expireSessions(); + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); + assert.equal(proxy.signIns.length, 0, "no new sign-in"); +}); + +test("rule 4: a tools/list the proxy cannot answer is a JSON-RPC error with the reason", async (t) => { + const bytebase = await startFakeBytebase(); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.listTools()).tools.length, 2); + await bytebase.close(); + await assert.rejects(proxy.client.listTools(), (err) => err.code !== undefined && /connect|reach|fetch/i.test(err.message)); +}); + +test("D5: an instance unreachable at startup is retried, then signs in and announces its tools", async (t) => { + const port = 53400 + Math.floor(Math.random() * 300); + const url = `http://127.0.0.1:${port}`; + const proxy = await connect({ url, home: freshHome(), port: nextPort++ }); + t.after(() => proxy.client.close()); + assert.match(proxy.client.getInstructions() ?? "", /could not be reached/); + // Long enough for the first opening to fail, so the session comes from a retry. + await new Promise((resolve) => setTimeout(resolve, 1500)); + + const bytebase = await startFakeBytebase({ port }); + t.after(() => bytebase.close()); + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); +}); + +test("States: a gateway's 502, 503 or 504 at startup reads as unreachable, not as a wrong URL", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + for (const status of [502, 503, 504]) { + bytebase.gatewayStatus = status; + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); + const instructions = proxy.client.getInstructions() ?? ""; + await proxy.client.close(); + assert.match(instructions, new RegExp(`could not be reached \\(HTTP ${status}`), `${status}: ${instructions}`); + } +}); + +test("D5: a first run behind a gateway answering 503 is retried, then signs in and announces its tools", { timeout: 30_000 }, async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + bytebase.gatewayStatus = 503; + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); + t.after(() => proxy.client.close()); + // Long enough for the first opening to fail, so the session comes from a retry. + await new Promise((resolve) => setTimeout(resolve, 1500)); + + bytebase.gatewayStatus = 0; + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); +}); + +test("D5: a first run whose OAuth discovery gets a gateway's 503 is retried, then signs in", { timeout: 30_000 }, async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + bytebase.gatewayPath = "/.well-known/oauth-authorization-server"; + bytebase.gatewayStatus = 503; + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); + t.after(() => proxy.client.close()); + // Long enough for the first opening to fail, so the session comes from a retry. + await new Promise((resolve) => setTimeout(resolve, 1500)); + + bytebase.gatewayStatus = 0; + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); +}); + +test("D5: a sign-in that fails after the browser opened is not retried, even on a gateway's 503", { timeout: 30_000 }, 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 url = await proxy.nextSignIn(); + // The SDK discovers the authorization server again before exchanging the code. + bytebase.gatewayPath = "/.well-known/oauth-authorization-server"; + bytebase.gatewayStatus = 503; + await completeSignIn(url); + await new Promise((resolve) => setTimeout(resolve, 1500)); + bytebase.gatewayStatus = 0; + + // A retry, if any, would start a new browser sign-in within a few seconds now that the gateway answers. + const again = await Promise.race([proxy.nextSignIn(), new Promise((resolve) => setTimeout(() => resolve(undefined), 5000))]); + assert.equal(again, undefined, "no second browser sign-in was started"); +}); + +test("D5: after an outage, tools/list reopens the session with the stored sign-in", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.listTools()).tools.length, 2); + await bytebase.goDown(); + const failed = await proxy.client.callTool({ name: "query_database", arguments: {} }); + assert.equal(failed.isError, true, "a call during the outage fails and drops the session"); + await assert.rejects(proxy.client.listTools(), "during the outage the client gets an error, not an empty list"); + await bytebase.comeBack(); + assert.deepEqual((await proxy.client.listTools()).tools.map((tool) => tool.name), ["query_database", "get_schema"]); + assert.equal(proxy.signIns.length, 0, "no new sign-in"); +}); + +test("D2: tools/list never waits on a sign-in in progress", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + + // Another live process holds this sign-in's lock, so the proxy's opening waits. + const instance = new URL(bytebase.url); + const lock = path.join(home, `${instance.hostname}_${instance.port}`, "sessions-client.json.lock"); + fs.mkdirSync(lock); + fs.writeFileSync(path.join(lock, "pid"), String(process.pid)); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + + const started = Date.now(); + assert.deepEqual((await proxy.client.listTools()).tools, [], "no session yet, so nothing to list"); + assert.ok(Date.now() - started < 3000, "answered without waiting for the opening"); + + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + fs.rmSync(lock, { recursive: true, force: true }); + await announced; + assert.equal((await proxy.client.listTools()).tools.length, 2); +}); + +test("D5: a reopen held up by another process's lock answers within the bound", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.listTools()).tools.length, 2); + + await bytebase.goDown(); + await proxy.client.callTool({ name: "query_database", arguments: {} }); + await bytebase.comeBack(); + const instance = new URL(bytebase.url); + const lock = path.join(home, `${instance.hostname}_${instance.port}`, "sessions-client.json.lock"); + fs.mkdirSync(lock); + fs.writeFileSync(path.join(lock, "pid"), String(process.pid)); + + const started = Date.now(); + await assert.rejects(proxy.client.listTools(), /still connecting/); + assert.ok(Date.now() - started < 15000, "bounded, not waiting on the lock"); + const listsBefore = bytebase.toolLists.length; + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + fs.rmSync(lock, { recursive: true, force: true }); + await announced; + assert.equal((await proxy.client.listTools()).tools.length, 2, "the client re-lists when told the reconnect finished"); + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.equal(bytebase.toolLists.length - listsBefore, 1, "the timed-out request was never sent"); +}); + +test("D2: a slow tools/list on an open session is not announced as a changed list", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.listTools()).tools.length, 2); + + let announcements = 0; + proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, () => announcements++); + bytebase.listDelayMs = 11000; + await assert.rejects(proxy.client.listTools(), /still connecting/); + await new Promise((resolve) => setTimeout(resolve, 1500)); + assert.equal(announcements, 0, "a slow answer on an open session changes nothing, so it is not announced"); +}); + +test("D9: logout deletes the sign-ins even when revocation stalls", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + await signInOnce(bytebase, home, nextPort++); + bytebase.revokeStalls = true; + const { execFile } = await import("node:child_process"); + const run = (command) => + new Promise((resolve, reject) => + execFile(process.execPath, [entry, command, "--url", bytebase.url], { env: { ...process.env, BYTEBASE_MCP_HOME: home }, timeout: 20000 }, (err, stdout) => + err ? reject(err) : resolve(stdout), + ), + ); + const started = Date.now(); + await run("logout"); + assert.ok(Date.now() - started < 15000, "logout did not wait on the stalled revocation"); + assert.deepEqual(JSON.parse(await run("status")).signIns, []); +}); + +test("D5: after the grant is revoked mid-session (reauthorize), the next call signs in again", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.callTool({ name: "get_schema", arguments: {} })).content[0].text, "ran get_schema"); + + bytebase.revokeAllTokens(); + const call = proxy.client.callTool({ name: "query_database", arguments: {} }); + await completeSignIn(await proxy.nextSignIn()); + const result = await call; + assert.equal(result.content[0].text, "ran query_database", "the call ran after the new sign-in"); +}); + +test("D5: a call in flight when the session is replaced still returns its result", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + assert.equal((await proxy.client.callTool({ name: "get_schema", arguments: {} })).content[0].text, "ran get_schema"); + + bytebase.callDelayMs = 4000; + const accepted = proxy.client.callTool({ name: "query_database", arguments: {} }); + await new Promise((resolve) => setTimeout(resolve, 300)); // Bytebase has accepted it + bytebase.revokeAllTokens(); + const next = proxy.client.callTool({ name: "get_schema", arguments: {} }); + const url = await proxy.nextSignIn(); + // The old session's event stream reconnects meanwhile; it must not start a sign-in of its own. + await new Promise((resolve) => setTimeout(resolve, 2500)); + await completeSignIn(url); + assert.equal((await next).content[0].text, "ran get_schema"); + assert.equal(proxy.signIns.length, 0, "the retired session started no second sign-in"); + const result = await accepted; + assert.equal(result.isError, undefined, "the accepted call was not cut off"); + assert.equal(result.content[0].text, "ran query_database"); + assert.equal(bytebase.toolCalls.filter((c) => c.name === "query_database").length, 1, "and was not sent twice"); +}); + +test("D5: a confirmation form stays up past the SDK's 60-second default", { timeout: 120000 }, async (t) => { + const bytebase = await startFakeBytebase({ streamed: true }); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + let withdrawn = false; + const proxy = await connect({ + url: bytebase.url, + home, + port, + // The user reads the form for longer than a minute, then approves. + onForm: async (_params, extra) => { + extra.signal.addEventListener("abort", () => (withdrawn = true)); + await new Promise((resolve) => setTimeout(resolve, 62000)); + return { action: "accept", content: {} }; + }, + }); + t.after(() => proxy.client.close()); + const result = await proxy.client.callTool({ name: "confirm_change", arguments: {} }, undefined, { timeout: 110000 }); + assert.equal(withdrawn, false, "the form was not taken down"); + assert.equal(result.content[0].text, "form accept", "the answer reached Bytebase"); +}); + +test("D5: a form Bytebase withdraws is taken down in the client", async (t) => { + const bytebase = await startFakeBytebase({ streamed: true }); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + bytebase.withdrawFormAfterMs = 500; + let withdrawnAt; + const shown = Date.now(); + const proxy = await connect({ + url: bytebase.url, + home, + port, + onForm: (_params, extra) => + new Promise((resolve) => { + extra.signal.addEventListener("abort", () => { + withdrawnAt = Date.now(); + resolve({ action: "cancel" }); + }); + }), + }); + t.after(() => proxy.client.close()); + const result = await proxy.client.callTool({ name: "confirm_change", arguments: {} }); + assert.match(result.content[0].text, /withdrawn/); + await new Promise((resolve) => setTimeout(resolve, 500)); + assert.ok(withdrawnAt !== undefined && withdrawnAt - shown < 5000, "the client was told to take the form down"); +}); + +test("rule 4: a successful reauthorize gets a note to reconnect, and Bytebase's text is kept", async (t) => { + const bytebase = await startFakeBytebase({ reauthorizeTool: true }); + t.after(() => bytebase.close()); + const home = freshHome(); + const port = nextPort++; + await signInOnce(bytebase, home, port); + const proxy = await connect({ url: bytebase.url, home, port }); + t.after(() => proxy.client.close()); + + const other = await proxy.client.callTool({ name: "get_schema", arguments: {} }); + assert.equal(other.content.length, 1, "other results pass through unchanged"); + + const result = await proxy.client.callTool({ name: "reauthorize", arguments: {} }); + assert.equal(result.content[0].text, "OAuth refresh grant revoked. Retry or reconnect this MCP server to run OAuth again."); + assert.equal(result.content.length, 2); + assert.match(result.content[1].text, /reconnect this MCP server/i); + assert.match(result.content[1].text, /sign in as the account you want/i); +}); + +test("rule 4: the reauthorize note makes no claim about what the client's instructions say", async (t) => { + const bytebase = await startFakeBytebase({ reauthorizeTool: true }); + t.after(() => bytebase.close()); + const proxy = await connect({ url: bytebase.url, home: freshHome(), port: nextPort++ }); + t.after(() => proxy.client.close()); + assert.match(proxy.client.getInstructions() ?? "", /sign in/i, "started signed out"); + const announced = new Promise((resolve) => proxy.client.setNotificationHandler(ToolListChangedNotificationSchema, resolve)); + await completeSignIn(await proxy.nextSignIn()); + await announced; + + const result = await proxy.client.callTool({ name: "reauthorize", arguments: {} }); + assert.equal(result.content.length, 2); + assert.match(result.content[1].text, /reconnect this MCP server/i); + assert.doesNotMatch(result.content[1].text, /account (is|was) named|still name|previous account/i, "the note makes no claim about the instructions"); +}); diff --git a/test/smoke.test.mjs b/test/smoke.test.mjs index 9af2952..475248b 100644 --- a/test/smoke.test.mjs +++ b/test/smoke.test.mjs @@ -1,63 +1,83 @@ -// The directory cold start: no BYTEBASE_URL, no instance. The server must -// still initialize and list its tools, and refuse calls with a clear message. +// The proxy's states without a session (docs/DESIGN.md, States), driven the way +// an MCP client drives it: spawn the built server over stdio. import { test } from "node:test"; import assert from "node:assert/strict"; +import fs from "node:fs"; import path from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { startFakeBytebase } 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")); -async function connect(env) { +async function connect(env, { form = false } = {}) { const transport = new StdioClientTransport({ command: process.execPath, args: [entry], - env: { ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("BYTEBASE_"))), ...env }, + env: { + ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("BYTEBASE_"))), + BYTEBASE_MCP_HOME: fs.mkdtempSync(path.join(import.meta.dirname, ".tmp-home-")), + BYTEBASE_MCP_NO_BROWSER: "1", + BYTEBASE_MCP_CALLBACK_PORT: String(52700 + Math.floor(Math.random() * 500)), + ...env, + }, stderr: "pipe", }); - const client = new Client({ name: "smoke", version: "0.0.0" }); + const client = new Client({ name: "smoke", version: "0.0.0" }, { capabilities: form ? { elicitation: { form: {} } } : {} }); await client.connect(transport); return client; } -test("lists the bundled tools without an instance", async () => { +test("S1: with no URL, lists the snapshot, runs nothing, and says no instance is connected", async (t) => { const client = await connect({}); - try { - const { tools } = await client.listTools(); - assert.ok(tools.length > 0, "bundle is empty: run `npm run sync-tools` against a Bytebase instance"); - for (const name of ["query_database", "get_schema", "propose_database_change", "search_api", "call_api"]) { - assert.ok(tools.some((t) => t.name === name), `missing tool ${name}`); - } - for (const t of tools) { - assert.equal(t.inputSchema?.type, "object", `${t.name} has no object inputSchema`); - assert.ok(t.description && t.description.length > 0, `${t.name} has no description`); - } - assert.ok((client.getInstructions() ?? "").includes("Bytebase"), "instructions are missing"); - } finally { - await client.close(); - } + t.after(() => client.close()); + + const instructions = client.getInstructions() ?? ""; + assert.ok(instructions.startsWith("No Bytebase instance is connected"), instructions); + assert.match(instructions, /BYTEBASE_URL/); + if (snapshot.instructions) assert.ok(instructions.endsWith(snapshot.instructions), "the snapshot's instructions follow the note"); + + const { tools } = await client.listTools(); + assert.ok(tools.length > 0); + assert.deepEqual( + tools.map((tool) => tool.name), + snapshot.tools.map((tool) => tool.name), + ); + + const result = await client.callTool({ name: tools[0].name, arguments: {} }); + assert.equal(result.isError, true); + assert.match(result.content[0].text, /BYTEBASE_URL/); }); -test("refuses a tool call without an instance", async () => { - const client = await connect({}); - try { - const result = await client.callTool({ name: "get_schema", arguments: {} }); - assert.equal(result.isError, true); - assert.match(result.content[0].text, /BYTEBASE_URL/); - } finally { - await client.close(); - } +test("S3: a configured Bytebase instance without a session lists nothing and says to sign in", async (t) => { + const bytebase = await startFakeBytebase(); + t.after(() => bytebase.close()); + + const formless = await connect({ BYTEBASE_URL: bytebase.url }); + t.after(() => formless.close()); + const instructions = formless.getInstructions() ?? ""; + assert.match(instructions, /sign in/i); + 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"); + + const withForm = await connect({ BYTEBASE_URL: bytebase.url }, { form: true }); + t.after(() => withForm.close()); + assert.ok(!(withForm.getInstructions() ?? "").includes("confirmation form")); }); -test("lists the bundled tools when the instance is unreachable", async () => { - const client = await connect({ BYTEBASE_URL: "http://127.0.0.1:9", BYTEBASE_MCP_HOME: path.join(import.meta.dirname, ".tmp-home"), BYTEBASE_MCP_NO_BROWSER: "1" }); - try { - const { tools } = await client.listTools(); - assert.ok(tools.length > 0); - const result = await client.callTool({ name: "get_schema", arguments: {} }); - assert.equal(result.isError, true); - assert.match(result.content[0].text, /cannot connect/); - } finally { - await client.close(); - } +test("S4: an unreachable instance and a server that is not Bytebase each say so and list nothing", async (t) => { + 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, []); + + const other = await startFakeBytebase({ resourceMetadata: false }); + t.after(() => other.close()); + const notBytebase = await connect({ BYTEBASE_URL: other.url }, { form: true }); + t.after(() => notBytebase.close()); + 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, []); });