agentleFS
worldnineworldnine/scrapbox-cosense-mcp/CLAUDE.md

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.

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
  1. Very specific:

    All tools are also available as CLI subcommands (get, list, search, create, url, insert, edit, delete-lines, delete, rewrite, context).

    line 36
  2. Very specific:

    Create release/vX.Y.Z branch, bump version in package.json + manifest.json + .claude-plugin/plugin.json

    line 129
  3. Distinctive:

    Create PR → CI passes → merge

    line 131

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 Inspector

Architecture

Tools (11, or 9 without COSENSE_ENABLE_DELETE)

ToolDescriptionAuth
get_pageRetrieve page content, metadata, and links-
list_pagesList pages with sorting and pagination (max 1000)-
search_pagesKeyword search (API limit: 100 results)-
create_pageCreate new page. Rejects if page already existsPAT/SID
get_page_urlGenerate URL from page title-
insert_linesInsert text after a target line (exact match). Appends to end if not foundPAT/SID
edit_linesReplace target line(s) (exact match, multi-line block supported). Errors if not found. matchAll replaces every occurrencePAT/SID
delete_linesDelete target line(s) (exact match, multi-line block supported). Refuses to delete the title line. Errors if not found. matchAll deletes every occurrencePAT/SID
delete_pageDelete a page. Registered only when COSENSE_ENABLE_DELETE=true. Errors if the page does not exist. dryRun previewsPAT/SID
rewrite_pageReplace 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/afterPAT/SID
get_smart_contextGet page + linked pages (1-hop/2-hop) in AI-optimized formatPAT/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 headers
  • src/routes/handlers/ — One handler module per tool
  • src/utils/format.ts — Response formatting, stringifyError, formatError
  • src/utils/sort.ts — Sorting with pinned page filtering
  • src/utils/project.ts — COSENSE_PROJECT_ALLOW_LIST check (checkProjectAllowed)
  • src/utils/markdown-converter.ts — Markdown → Scrapbox conversion (uses md2sb)
  • src/types/ — API response and MCP request/response type definitions
  • src/cli.ts — CLI entry point (args → CLI mode, no args → MCP server)
  • src/index.ts — Server entry point (createServer(); TRANSPORT=http switches stdio to HTTP)
  • src/http-server.ts — Streamable HTTP transport: per-session servers, session ownership, JSON-RPC errors for bad bodies
  • src/auth/ — OAuth 2.1 authorization server for the HTTP transport (config.ts reads MCP_*, provider.ts the flow, store.ts clients/tokens, authenticator.ts the ConsentAuthenticator)

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 websocket patch() of @cosense/std. The edit API refuses cookie-authenticated writes (CrossOriginWriteNotAllowedError, and /api/users/me no longer returns a CSRF token), and the websocket accepts only cookie auth, so neither path can serve both. Handlers pass a patch-shaped update callback and never know which path runs
  • Credentials come only from COSENSE_MCP_PAT and COSENSE_SID (a value starting with cs_ is sent as a Service Account key). The token variable is COSENSE_MCP_PAT, not the official CLI's COSENSE_PAT: people export COSENSE_PAT in their shell for the CLI, MCP servers inherit that environment, and reading it would silently give this server write access. COSENSE_SID wins when both are set, so adding a token never changes an existing SID setup; switching to the token means removing COSENSE_SID. ~/.cosense/settings.json, which cosense login of 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
  • writePage keeps patch()'s contract on the edit API, for callbacks that return an array (every handler does; patch's undefined, 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 without pageId, 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 409 NotFastForward (the page changed after the preview) or a preview whose commitId differs 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 _update within one changed region, top to bottom, so line IDs (and authorship) survive; leftovers become _delete or _insert before the next kept line (_end at 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_page rejects existing pages (persistent === true). Without this check, patch() silently replaces all content since it's a diff-update API
  • insert_lines uses exact match. Partial match risks inserting at unintended lines
  • edit_lines / delete_lines default to matchAll: false. Repeated lines (bullet markers, blank lines) are common, so replacing/deleting every occurrence by default would exceed what the caller asked for
  • edit_lines / delete_lines treat a newline-containing targetLineText as a contiguous block. Matching is non-overlapping with matchAll, so n lines can become m lines (edit) or be removed together (delete)
  • delete_lines refuses 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 the COSENSE_ENABLE_DELETE gate on delete_page. It returns an error pointing to delete_page instead
  • delete_page and rewrite_page are gated by COSENSE_ENABLE_DELETE at 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_lines require exact matches, which only succeed if the caller has read the page. delete_page / rewrite_page act on the whole page regardless, so they get the opt-in gate
  • delete_page checks 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 — persistent does, the same way create_page decides. Without this check a delete against a missing page reports success
  • rewrite_page inverts 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 is delete_page's job)
  • delete_page and rewrite_page support dryRun, which report the line counts (and previews) without calling patch() at all. There is no undo, so an agent should be able to look before it acts
  • insert_lines and edit_lines/delete_lines differ when the target is missing, deliberately. insert_lines appends to the end, since "add this text" still has a sensible landing spot. edit_lines/delete_lines error and leave the page untouched, since "replace/delete this line" has no fallback
  • COSENSE_PROJECT_ALLOW_LIST is checked in every handler, right after the project name is resolved, via checkProjectAllowed() in src/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 their try. src/__tests__/handlers/project-allow-list.test.ts enumerates 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's defaultProjectName argument. The CLI passes --project=NAME as defaultProjectName too, 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 websocket patch() returns a Result the same way). Must check result.ok
  • user is the page's creator and lastUpdateUser its last editor (as @cosense/types defines them). Every output builds the creator/editor lines through formatEditorLines in src/utils/format.ts, which omits a line when the name is unknown instead of printing undefined
  • Default sort is updated. Aligned across API, display, and user expectations. The API puts pinned pages first regardless of sort (confirmed with villagepump on 2026-11-14). Lists that include pinned pages, including startup resources, send the requested sort and fetch once with skip: 0, limit: min(skip + limit + 100, 1000). Only pinned pages are sorted locally and merged into the unpinned API order before applying skip and limit. Numeric sorts are descending; title uses the existing ascending localeCompare, 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 plus skip + limit exceeds 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; skip counts API entries before filtering.
  • The HTTP transport refuses to start without authentication unless MCP_ALLOW_UNAUTHENTICATED=true, and OAuth needs both MCP_PUBLIC_URL and MCP_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 touching provider.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_SID resolution 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_pages and 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 minus relatedPages — 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_page therefore costs one extra request only when the cache is cold, and --compact outputs never look names up. The E2E tests run only with COSENSE_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 API
  • COSENSE_SID — Session ID (connect.sid). Takes precedence over COSENSE_MCP_PAT. Writes go through the websocket
  • COSENSE_TOOL_SUFFIX — Tool name suffix for multiple server instances
  • COSENSE_CONVERT_NUMBERED_LISTS — Convert numbered lists to bullet lists
  • COSENSE_ENABLE_DELETE — Register delete_page/rewrite_page and the delete/rewrite CLI commands (opt-in)
  • COSENSE_PROJECT_ALLOW_LIST — Comma-separated projects that projectName/--project may target. COSENSE_PROJECT_NAME is 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 stdio
  • MCP_PUBLIC_URL + MCP_OAUTH_PASSPHRASE — Turn on OAuth 2.1 for the HTTP transport. MCP_OAUTH_STORE persists clients and tokens
  • MCP_ALLOWED_HOSTS / MCP_TRUST_PROXY — Host allow list (replaces the localhost default) and Express trust proxy (a hop count or address; the string true makes Express throw at startup) for running behind a reverse proxy
  • MCP_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

  1. Create release/vX.Y.Z branch, bump version in package.json + manifest.json + .claude-plugin/plugin.json
    • Note: the MCP serverInfo.version is read from package.json at runtime, so no separate bump is needed for src/index.ts
  2. Create PR → CI passes → merge
  3. 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 .js extensions
  • Dual config: tsconfig.json (dev) and tsconfig.build.json (prod, excludes tests)

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.