scrapbox-cosense-mcp
CLAUDE.md55 starsChanged 18 months agoMITView on GitHub
MCP server for Cosense (Scrapbox). Also works as a CLI. All tools are also available as CLI subcommands (get, list, search, create, url, insert, edit, delete-lines, delete, rewrite, context). delete and rewrite require COSENSE_ENABLE_DELETE=true and support --dry-run. Run scrapbox-cosense-mcp <command> --help for usage. Key flags: skills/scrapbox/SKILL.md defines a Claude Code skill that wraps the CLI. When users invoke /cosense, Claude Code reads SKILL.md and executes CLI commands via Bash. Keep SKILL.md concise — details should be discoverable via --help. .claude-plugin/…
- Reads credentials
- Installs packages
In this repositoryOne other file it gives its agents.
- cosenseSkill
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 36
All tools are also available as CLI subcommands (get, list, search, create, url, insert, edit, delete-lines, delete, rewrite, context).
- Very specific: line 129
Create release/vX.Y.Z branch, bump version in package.json + manifest.json + .claude-plugin/plugin.json
- Distinctive: line 131
Create PR → CI passes → merge
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
MCP server for Cosense (Scrapbox). Also works as a CLI.
Commands
npm run build # TypeScript → JavaScript (uses tsconfig.build.json)
npm run watch # Auto-rebuild during development
npm run test # Run Jest tests (no real API calls)
COSENSE_E2E=true npm run test # Also run the E2E tests against the real Cosense API — sparingly, e.g. once before merging
npm run lint # ESLint (console.log triggers warning)
npm run inspector # Debug with MCP InspectorArchitecture
Tools (11, or 9 without COSENSE_ENABLE_DELETE)
| Tool | Description | Auth |
get_page | Retrieve page content, metadata, and links | - |
list_pages | List pages with sorting and pagination (max 1000) | - |
search_pages | Keyword search (API limit: 100 results) | - |
create_page | Create new page. Rejects if page already exists | PAT/SID |
get_page_url | Generate URL from page title | - |
insert_lines | Insert text after a target line (exact match). Appends to end if not found | PAT/SID |
edit_lines | Replace target line(s) (exact match, multi-line block supported). Errors if not found. matchAll replaces every occurrence | PAT/SID |
delete_lines | Delete target line(s) (exact match, multi-line block supported). Refuses to delete the title line. Errors if not found. matchAll deletes every occurrence | PAT/SID |
delete_page | Delete a page. Registered only when COSENSE_ENABLE_DELETE=true. Errors if the page does not exist. dryRun previews | PAT/SID |
rewrite_page | Replace a page's entire content. Registered only when COSENSE_ENABLE_DELETE=true. Errors if the page does not exist or content is empty. dryRun previews before/after | PAT/SID |
get_smart_context | Get page + linked pages (1-hop/2-hop) in AI-optimized format | PAT/SID |
CLI
All tools are also available as CLI subcommands (get, list, search, create, url, insert, edit, delete-lines, delete, rewrite, context). delete and rewrite require COSENSE_ENABLE_DELETE=true and support --dry-run. Run scrapbox-cosense-mcp <command> --help for usage. Key flags:
--compact— Token-efficient output (85% smaller for list)--json— JSON output--project=NAME— Override project name
Skill (SKILL.md)
skills/scrapbox/SKILL.md defines a Claude Code skill that wraps the CLI. When users invoke /cosense, Claude Code reads SKILL.md and executes CLI commands via Bash. Keep SKILL.md concise — details should be discoverable via --help.
Claude Code Plugin
.claude-plugin/ (plugin.json + marketplace.json) enables installation via /plugin marketplace add worldnine/scrapbox-cosense-mcp. The marketplace resolves the plugin from the npm package, so .claude-plugin/, .mcp.json, and skills/ must be listed in package.json files — a plugin fix only takes effect after the next npm release.
Desktop Extensions (.mcpb)
manifest.json + .mcpbignore enable Claude Desktop Extensions packaging. The .mcpb file is auto-built and attached to GitHub Releases by release-mcpb.yml. To build locally: npm install --omit=dev && npx @anthropic-ai/mcpb pack.
Directory Structure
src/cosense.ts— Scrapbox REST API client (reads)src/page-writer.ts—writePage: writes through the edit API (PAT / Service Account) or the websocket (SID)src/utils/auth.ts— Credential resolution (resolveCredential) and request headerssrc/routes/handlers/— One handler module per toolsrc/utils/format.ts— Response formatting,stringifyError,formatErrorsrc/utils/sort.ts— Sorting with pinned page filteringsrc/utils/project.ts—COSENSE_PROJECT_ALLOW_LISTcheck (checkProjectAllowed)src/utils/markdown-converter.ts— Markdown → Scrapbox conversion (usesmd2sb)src/types/— API response and MCP request/response type definitionssrc/cli.ts— CLI entry point (args → CLI mode, no args → MCP server)src/index.ts— Server entry point (createServer();TRANSPORT=httpswitches stdio to HTTP)src/http-server.ts— Streamable HTTP transport: per-session servers, session ownership, JSON-RPC errors for bad bodiessrc/auth/— OAuth 2.1 authorization server for the HTTP transport (config.tsreadsMCP_*,provider.tsthe flow,store.tsclients/tokens,authenticator.tstheConsentAuthenticator)
Design Decisions
- All page writes go through
writePage(src/page-writer.ts), which picks the path by credential: a PAT or Service Account uses the edit API (/api/pages/v2/<project>/page-edit-for-ai/preview→submit), a SID uses the websocketpatch()of@cosense/std. The edit API refuses cookie-authenticated writes (CrossOriginWriteNotAllowedError, and/api/users/meno longer returns a CSRF token), and the websocket accepts only cookie auth, so neither path can serve both. Handlers pass apatch-shaped update callback and never know which path runs - Credentials come only from
COSENSE_MCP_PATandCOSENSE_SID(a value starting withcs_is sent as a Service Account key). The token variable isCOSENSE_MCP_PAT, not the official CLI'sCOSENSE_PAT: people exportCOSENSE_PATin their shell for the CLI, MCP servers inherit that environment, and reading it would silently give this server write access.COSENSE_SIDwins when both are set, so adding a token never changes an existing SID setup; switching to the token means removingCOSENSE_SID.~/.cosense/settings.json, whichcosense loginof the official CLI writes, is deliberately not read: it would give this server write access the moment someone logs in with the official CLI, even where they gave this server no credential on purpose (read-only use of public projects), and a PAT reaches every project the user can see. Write power has to be configured for this server explicitly writePagekeepspatch()'s contract on the edit API, for callbacks that return an array (every handler does;patch'sundefined, Promise, and{ lines, pin }forms are not supported): returning the same array writes nothing,[]deletes the page ({ deleted: true }), a non-persistent page is created by inserting every line withoutpageId, and a conflict re-reads the page and calls the callback again (up to 3 times). Callbacks must reset their state on every call. A conflict is either a 409NotFastForward(the page changed after the preview) or a preview whosecommitIddiffers from the one read: the preview request carries no base revision, so without that check an edit made between the read and the preview would be overwritten by line ID. A token write costs three requests (read, preview, submit)- The edit-API diff pairs removed and added lines 1:1 as
_updatewithin one changed region, top to bottom, so line IDs (and authorship) survive; leftovers become_deleteor_insertbefore the next kept line (_endat the bottom). Inserts are anchored on kept lines only, so they never point at a line deleted in the same request - Tests unset
COSENSE_MCP_PAT(src/__tests__/setup-env.ts), so a token in the developer's shell never reaches the edit API from a test create_pagerejects existing pages (persistent === true). Without this check,patch()silently replaces all content since it's a diff-update APIinsert_linesuses exact match. Partial match risks inserting at unintended linesedit_lines/delete_linesdefault tomatchAll: false. Repeated lines (bullet markers, blank lines) are common, so replacing/deleting every occurrence by default would exceed what the caller asked foredit_lines/delete_linestreat a newline-containingtargetLineTextas a contiguous block. Matching is non-overlapping withmatchAll, so n lines can become m lines (edit) or be removed together (delete)delete_linesrefuses to delete the title line (the first line). Deleting it would rename the page — or remove it entirely if nothing else remains — which would bypass theCOSENSE_ENABLE_DELETEgate ondelete_page. It returns an error pointing todelete_pageinsteaddelete_pageandrewrite_pageare gated byCOSENSE_ENABLE_DELETEat tool-registration time, not just at call time. This server is often placed in a shared MCP configuration, so an unset variable means the tools never appear in the tool list and cannot be called by mistake. The handlers check the variable again, so the CLI and direct calls are covered too- The gate boundary is "does the caller have to name the content it destroys".
insert_lines/edit_lines/delete_linesrequire exact matches, which only succeed if the caller has read the page.delete_page/rewrite_pageact on the whole page regardless, so they get the opt-in gate delete_pagechecks existence before deleting. The REST API returns a title line even for a page that was never created, so line count cannot tell existence apart —persistentdoes, the same waycreate_pagedecides. Without this check a delete against a missing page reports successrewrite_pageinverts the existence check: it rejects pages that do NOT exist (persistent !== true). A title typo must not silently create a new page, and it must reject empty content (deletion isdelete_page's job)delete_pageandrewrite_pagesupportdryRun, which report the line counts (and previews) without callingpatch()at all. There is no undo, so an agent should be able to look before it actsinsert_linesandedit_lines/delete_linesdiffer when the target is missing, deliberately.insert_linesappends to the end, since "add this text" still has a sensible landing spot.edit_lines/delete_lineserror and leave the page untouched, since "replace/delete this line" has no fallbackCOSENSE_PROJECT_ALLOW_LISTis checked in every handler, right after the project name is resolved, viacheckProjectAllowed()insrc/utils/project.ts. Handlers are the only point shared by the MCP dispatcher, the CLI, and direct calls, so a check in the dispatcher alone would miss the other two. The helper returns an error message instead of throwing because four handlers resolve the project name outside theirtry.src/__tests__/handlers/project-allow-list.test.tsenumerates every handler file, so adding a tool without the check fails the test- The implicit allowance of the default project reads
process.env.COSENSE_PROJECT_NAME, not the handler'sdefaultProjectNameargument. The CLI passes--project=NAMEasdefaultProjectNametoo, so comparing against the argument would let every CLI call through - An allow list that is set but empty (
"",",,,") restricts to the default project rather than falling back to unrestricted. Whoever set the variable meant to restrict, and only an unset variable means "no fence" writePage()returns{ ok: true } | { ok: false; err: string }, not throw (the websocketpatch()returns aResultthe same way). Must checkresult.okuseris the page's creator andlastUpdateUserits last editor (as@cosense/typesdefines them). Every output builds the creator/editor lines throughformatEditorLinesinsrc/utils/format.ts, which omits a line when the name is unknown instead of printingundefined- Default sort is
updated. Aligned across API, display, and user expectations. The API puts pinned pages first regardless ofsort(confirmed with villagepump on 2026-11-14). Lists that include pinned pages, including startup resources, send the requestedsortand fetch once withskip: 0,limit: min(skip + limit + 100, 1000). Only pinned pages are sorted locally and merged into the unpinned API order before applyingskipandlimit. Numeric sorts are descending; title uses the existing ascendinglocaleCompare, whose collation may differ from the API (not verified). Equal values put pinned pages first while preserving each input sequence's order. If the pinned count plusskip + limitexceeds the fetched amount, the top results or page positions may be inaccurate; the single-request limit is accepted, as before. Excluding pinned pages preserves the API order and reuses list metadata without an extra request;skipcounts API entries before filtering. - The HTTP transport refuses to start without authentication unless
MCP_ALLOW_UNAUTHENTICATED=true, and OAuth needs bothMCP_PUBLIC_URLandMCP_OAUTH_PASSPHRASE(one alone is a startup error). An auth setting that is written down but not in effect must never reach the network - OAuth 2.1 is the only client authentication over HTTP, and the authorization server runs in the same process. Claude.ai and ChatGPT accept nothing else for MCP servers (a static bearer token was considered and dropped in #77), and few external IdPs accept Dynamic Client Registration. Registration is open to anyone who knows the URL, so the consent screen asks for
MCP_OAUTH_PASSPHRASE - Who gets through the consent screen is decided by a
ConsentAuthenticator(src/auth/authenticator.ts). Upstream has one implementation (the passphrase); the interface exists so a multi-user fork can swap it without touchingprovider.ts. Keep it when refactoring - An MCP session is bound to the grant that opened it (
grantId, which survives refresh-token rotation, so a session does not drop every hour). A request with another grant's token gets 404 for that session, not 403, so the session's existence does not leak - Every HTTP client acts with the one Cosense credential in the server's environment, the same
COSENSE_MCP_PAT/COSENSE_SIDresolution as stdio. The docs recommend a PAT for HTTP (a SID expires, and every tool call fails until someone replaces it), but a SID is not forbidden (#77) - Keep the request count low; Cosense is a free API, not ours to load.
list_pagesand the startup resource list use the page-list API as is and never fetch each page (that used to send 100–1000+ concurrent requests per call). Page reads use/api/pages/v2/, which returns the same body as v1 minusrelatedPages— unused here, and most of v1's payload (364 KB against 13.7 KB for villagepump's 井戸端). Creator and editor names come from the project member list (/api/projects/:project/users, cached per process for 5 minutes, failures included), because the page and page-list APIs return user IDs only since January 2026;get_pagetherefore costs one extra request only when the cache is cold, and--compactoutputs never look names up. The E2E tests run only withCOSENSE_E2E=true, because running them whenever credentials sit in the shell hit the Smart Context rate limit (429) during development
Environment Variables
See README.md. Key variables:
COSENSE_PROJECT_NAME— Target project (required)COSENSE_MCP_PAT— Personal Access Token (recommended) for private projects, writes, and Smart Context. Writes go through the edit APICOSENSE_SID— Session ID (connect.sid). Takes precedence overCOSENSE_MCP_PAT. Writes go through the websocketCOSENSE_TOOL_SUFFIX— Tool name suffix for multiple server instancesCOSENSE_CONVERT_NUMBERED_LISTS— Convert numbered lists to bullet listsCOSENSE_ENABLE_DELETE— Registerdelete_page/rewrite_pageand thedelete/rewriteCLI commands (opt-in)COSENSE_PROJECT_ALLOW_LIST— Comma-separated projects thatprojectName/--projectmay target.COSENSE_PROJECT_NAMEis always allowed. Unset = unrestricted; set but empty = default project only (opt-in)TRANSPORT=http— Serve Streamable HTTP at/mcp(PORT,MCP_HTTP_HOST) instead of stdioMCP_PUBLIC_URL+MCP_OAUTH_PASSPHRASE— Turn on OAuth 2.1 for the HTTP transport.MCP_OAUTH_STOREpersists clients and tokensMCP_ALLOWED_HOSTS/MCP_TRUST_PROXY—Hostallow list (replaces the localhost default) and Expresstrust proxy(a hop count or address; the stringtruemakes Express throw at startup) for running behind a reverse proxyMCP_ALLOW_UNAUTHENTICATED— Let the HTTP transport start without authentication (local use only)
CI/CD & Release
GitHub Actions
- pr.yml — Quality check on PRs (lint → test → build)
- security-scan.yml — Security scan
- auto-release.yml —
release/v*PR merge → auto-create tag + GitHub Release - publish-npm.yml —
v*tag push → auto-publish to npm - release-mcpb.yml — GitHub Release → auto-build and attach .mcpb
Release Process
- Create
release/vX.Y.Zbranch, bump version inpackage.json+manifest.json+.claude-plugin/plugin.json- Note: the MCP
serverInfo.versionis read frompackage.jsonat runtime, so no separate bump is needed forsrc/index.ts
- Note: the MCP
- Create PR → CI passes → merge
- Everything after merge is automatic (tag → npm → GitHub Release → .mcpb)
TypeScript
- Strict mode: includes
exactOptionalPropertyTypes: true - Path aliases:
@/→src/(configured in both TypeScript and Jest; runtime uses relative paths) - ESM: imports use
.jsextensions - Dual config:
tsconfig.json(dev) andtsconfig.build.json(prod, excludes tests)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

