# Agent Protocol **Server:** obsidian-mcp-server **Version:** 3.9.0 **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.22` **Engines:** Bun ≥1.4.4, Node ≥24.0.0 **MCP SDK:** `@modelcontextprotocol/server` ^2.4.0 **Zod:** ^4.6.7 > **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only. --- ## What's Next? When the user asks what to do next, what's left, or needs direction, suggest relevant options based on the current project state: 1. **Re-run the `setup` skill** — ensures CLAUDE.md, skills, structure, and metadata are populated and up to date with the current codebase 2. **Run the `design-mcp-server` skill** — if the tool/resource surface hasn't been mapped yet, work through domain design 3. **Add tools/resources/prompts** — scaffold new definitions using the `add-tool`, `add-app-tool`, `add-resource`, `add-prompt` skills 4. **Add services** — scaffold domain service integrations using the `add-service` skill 5. **Add tests** — scaffold tests for existing definitions using the `add-test` skill 6. **Field-test definitions** — exercise tools/resources/prompts with real inputs using the `field-test` skill, get a report of issues and pain points 7. **Run `devcheck`** — lint, format, typecheck, and security audit 8. **Run the `security-pass` skill** — audit handlers for MCP-specific security gaps: output injection, scope blast radius, input sinks, tenant isolation 9. **Run the `polish-docs-meta` skill** — finalize README, CHANGELOG, metadata, and agent protocol for shipping 10. **Run the `maintenance` skill** — investigate changelogs, adopt upstream changes, and sync skills after `bun update --latest` Tailor suggestions to what's actually missing or stale — don't recite the full list every time. --- ## Core Rules - **Logic throws, framework catches.** Tool/resource handlers are pure — throw on failure, no `try/catch`. Plain `Error` is fine; the framework catches, classifies, and formats. Use error factories (`notFound()`, `validationError()`, etc.) when the error code matters. - **Use `ctx.log`** for request-scoped logging. No `console` calls. - **The delete confirmation is opt-in; when on, it is gated on a consent record.** `OBSIDIAN_DELETE_ELICITATION` (default `false`) decides whether `obsidian_delete_note` confirms through `ctx.requestInput`. Off is the default for two reasons: a client that declares elicitation but cannot render the form declines every round automatically, which the server cannot tell from a real decline (#151), and the round forces a stateful HTTP session, which locks out `MCP_SESSION_MODE=stateless`. Off, `OBSIDIAN_WRITE_PATHS` / `OBSIDIAN_DENY_PATHS` / `OBSIDIAN_READ_ONLY` bound what a delete can reach — the same bound `obsidian_write_note` with `overwrite: true` has — and `destructiveHint` stays for client-side approval. The mode is the operator's choice alone: never derive it from `ctx.clientCapabilities` or from a decline. On, the handler redeems (reads and deletes) the `ctx.state` record named by `ctx.inputs.state()` before anything else, checks write scope on the resolved path before it reads the note or asks, and acts on the `ctx.inputs` answer only when that record deep-equals `{ operation, clientId, subject, target, contentHash }` for this call; otherwise it stores a fresh record (`ttl: 600`) and `return ctx.requestInput(...)` with the record id as `requestState`. An answer alone is never proof the user was asked. Never `await` user input mid-handler. - **All Obsidian access goes through `getObsidianService()`.** No direct `fetch()` calls to the Local REST API in tools/resources — the service centralizes auth, TLS, timeouts, and `ctx.signal` propagation. - **Secrets in env vars only.** `OBSIDIAN_API_KEY` is required; never hardcoded. - **Cut noise.** Add only what earns its place: no speculative generality, no guards for states the framework already prevents (Zod-validated params, classified errors), no abstraction until a third caller proves it, no option nothing sets. - **Command-palette tools are opt-in.** `obsidian_list_commands` and `obsidian_execute_command` are callable only when `OBSIDIAN_ENABLE_COMMANDS=true` — Obsidian commands are opaque and can be destructive. When the flag is unset, the entry point wraps both with `disabledTool()` so they're absent from `tools/list` (LLM can't invoke) but visible in the operator-facing manifest with a hint to enable them. - **Path-policy gating goes through `PathPolicy`.** Every path-taking method on `ObsidianService` calls `policy.assertReadable` / `assertWritable` before the upstream HTTP call; `listFiles` gates with `assertListable` and filters entries with `filterListing` (readable entries plus folders on the way to the scope), so every listing consumer inherits the scope; `obsidian_search_notes` filters hits via `svc.policy.filterReadable`. `OBSIDIAN_DENY_PATHS` wins over every allow rule, and setting it turns on `restrictsReads`, so a deny list alone routes listings, tag counts, and JSONLogic through the scoped paths. Under `policy.restrictsReads`, `searchJsonLogic` never sends the caller's tree upstream: one `/search/` guarded by `readScopePattern` fetches the readable notes' contexts (plus, when the tree names `content`, one `GET /vault/{path}` per readable note through the service-wide `#bodyReads` pacer, at most `BODY_READ_CONCURRENCY` (32) in flight, evaluated in batches of at most 32 MiB), `filterReadable` gates them, and the note contexts carry no `links` / `backlinks` / `unresolvedLinks` (a tree whose fixed `var`, `missing`, or `missing_some` key names one fails `link_fields_unavailable` before any request; a computed key reads `null`). `createJsonLogicEvaluation` runs the tree on a worker thread with the plugin's operators, bounded by depth, a per-note build budget, a per-search kept-result budget, a 10 s evaluation deadline, and `SCOPED_SEARCH_DEADLINE_MS` (45 s) over the whole search (`logic_too_costly`; a note too deep to hand to the worker is `note_too_deep`), so no hit, result, or error reads a note outside the scope. Text mode under `restrictsReads` never calls `/search/simple/`: one guarded `/search/` names the readable candidates, one `GET` per candidate body, and `SimpleSearch` (`simple-search.ts`, a port of Obsidian's `prepareSimpleSearch`) builds the hits and windows under the same 45 s deadline (`text_search_too_costly`; `context_length_too_large` counts the response the plugin would send for the readable matches alone, every match's offsets and framing with its window, against V8's longest string). A scoped walk evaluates once: `pageText` and `pageJsonLogic` store the hit list a first page computed in one store (5 min past the last read, `WALK_STORE_CHARS` (32 Mi characters) across walks, least recently read evicted first), and the walk id rides `nextCursor`; a text entry is keyed by `query`, `contextLength`, and `maxMatchesPerHit` (never the scope, fixed per process, nor `pathPrefix`, applied per page) and holds copied windows, since a window sliced from a note body keeps the whole body alive. Under `restrictsReads` the `omnisearch` mode is withheld (`omnisearchAvailability`): absent from the `mode` enum, the description, and `instructions`, and nothing reaches the Omnisearch URL, the startup probe included, since Omnisearch ranks and selects its results over the whole vault. `listTags` reads per-note tags from the same readable contexts, with no evaluation. An `active` / `periodic` target is gated on the path it resolves to, under the target's label: `resolveTarget` / `pinTarget` return a `PathTarget` whose `resolvedFrom` the asserts take, so a denial names `(active file)` or `daily note for 2026-10-01`, never a path the caller did not send, and a tool that reads a target then writes it writes to that pinned path rather than resolving the target again. Don't bypass this — `OBSIDIAN_READ_PATHS` / `OBSIDIAN_WRITE_PATHS` / `OBSIDIAN_DENY_PATHS` / `OBSIDIAN_READ_ONLY` are the single chokepoint, and `path_forbidden` is declared on every path-taking tool's `errors[]` contract. A `denied_path` denial carries no `activeScope`, and no agent-facing surface (error data, `instructions`) names a deny prefix; only the startup log lists them. - **Close the loop on issues.** When implementing work tracked by a GitHub issue, comment on the issue with what landed and close it. Do both — a comment without a close leaves stale issues open; a close without a comment leaves no record of what shipped. The comment is for future readers — state the concrete changes, not the conversation that produced them. --- ## Patterns ### Tool — `obsidian_list_tags` A small read-only tool that wraps a single service call, normalizes the response into the output schema, and renders a markdown twin in `format()`. Reduced for illustration — the live definition also carries `nameRegex` / `minCount` / `limit` inputs, the count-descending sort and cap they feed, an `errors[]` contract, and an `enrichment` block. ```ts import { tool, z } from '@cyanheads/mcp-ts-core'; import { getObsidianService } from '@/services/obsidian/obsidian-service.js'; export const obsidianListTags = tool('obsidian_list_tags', { description: 'List every tag found across the vault, with usage counts. Includes hierarchical parents — `work/tasks` contributes to both `work` and `work/tasks`.', annotations: { readOnlyHint: true, idempotentHint: true }, input: z.object({}), output: z.object({ tags: z .array( z.object({ name: z.string().describe('Tag name without the leading `#`.'), count: z .number() .describe( 'Times the tag, or a tag nested under it, occurs across the vault. When OBSIDIAN_READ_PATHS or OBSIDIAN_DENY_PATHS is set: the number of readable notes carrying the tag or a tag nested under it.', ), }).describe('A tag with its usage count.'), ) .describe('Matching tags ordered by `count` descending.'), }), auth: ['tool:obsidian_list_tags:read'], async handler(_input, ctx) { const svc = getObsidianService(); const tags = await svc.listTags(ctx); return { tags: tags.map((t) => ({ name: t.name, count: t.count })) }; }, // format() populates content[] — the markdown twin of structuredContent. // Different clients read different surfaces (Claude Code → structuredContent, // Claude Desktop → content[]); both must carry the same data. // Enforced at lint time: every field in `output` must appear in the rendered text. format: (result) => { if (result.tags.length === 0) { return [{ type: 'text', text: '_No tags found in the vault._' }]; } const lines = [`**${result.tags.length} tags**`, '']; for (const t of result.tags) lines.push(`- \`#${t.name}\` (${t.count})`); return [{ type: 'text', text: lines.join('\n') }]; }, }); ``` For a destructive tool with optional human-in-the-loop confirmation, see `obsidian-delete-note.tool.ts`. `src/index.ts` builds it with `buildDeleteNoteTool({ elicitation })` from `OBSIDIAN_DELETE_ELICITATION`, so the description states the active mode; the exported `obsidianDeleteNote` is the off build, kept as the specimen the definition linter and tests import. Both modes check write scope on the resolved path, then read the note before the DELETE. That read is the folder guard (`path_is_directory`), since the Local REST API's `DELETE` on a folder path removes the folder and everything in it. It is also the exact-case guard, so it goes through `note+json` (`getNoteJson`), never the raw-markdown read. On a case-insensitive filesystem the raw read and the plugin v4.x `DELETE` (`adapter.exists` + `adapter.remove`) case-fold, so a wrong-case path would read and then permanently remove the differently-cased note. `note+json` resolves through Obsidian's case-sensitive vault index on v4.x and v5.x, so a wrong-case path fails `note_missing` before any DELETE, with near matches listed in `suggestions` and never substituted. With the confirmation on, it redeems a single-use consent record from `ctx.state` (bound to the operation, the caller, the resolved path, and a SHA-256 of the note's content), suspends with `ctx.requestInput` for an embedded `elicitation/create` round when no matching record backs the answer, and branches on `ctx.inputs.view()` so a declined prompt on a matching round fails instead of re-asking. Only the confirming build declares `cancelled` in `errors[]`, since the off build never throws it. Both builds carry the `destructiveHint` annotation. Pattern: framework `api-context` § Consent gates. ### Resource — `obsidian://status` ```ts import { resource, z } from '@cyanheads/mcp-ts-core'; import { getObsidianService } from '@/services/obsidian/obsidian-service.js'; export const obsidianStatus = resource('obsidian://status', { name: 'obsidian-status', description: 'Server reachability, plugin version, and auth status of the Obsidian Local REST API.', mimeType: 'application/json', params: z.object({}), output: z.object({ status: z.string().describe('Upstream reported status string.'), service: z.string().describe('Service identifier returned by the plugin.'), authenticated: z.boolean().describe('Whether the configured OBSIDIAN_API_KEY is recognized.'), }), auth: ['resource:obsidian-status:read'], async handler(_params, ctx) { const svc = getObsidianService(); return await svc.getStatus(ctx); }, }); ``` For a parameterized resource, see `obsidian-vault-note.resource.ts` (`obsidian://vault/{+path}`) — the `{+path}` segment captures everything after `/vault/` including slashes. ### Prompt This server exposes a CRUD/search surface; no recurring multi-turn pattern benefits from a structured prompt template, so `allPromptDefinitions` is intentionally empty. Add one with `prompt('name', { ... })` if a workflow emerges. ### Server config — `OBSIDIAN_*` env vars ```ts // src/config/server-config.ts — lazy-parsed, separate from framework config import { z } from '@cyanheads/mcp-ts-core'; import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config'; /** true/false/1/0/yes/no/on/off, case-insensitive; anything else fails startup. */ const envBoolean = z.union([z.boolean(), z.stringbool()]); const ServerConfigSchema = z.object({ apiKey: z.string().min(1).describe('Bearer token for the Obsidian Local REST API plugin.'), baseUrl: z.string().url().default('http://127.0.0.1:27123'), verifySsl: envBoolean.default(false), requestTimeoutMs: z.coerce.number().int().positive().default(30_000), enableCommands: envBoolean.default(false), /** Path-policy lists — comma-separated, prefix-based, case-insensitive. Allowlists unset = full vault; the deny list wins over both. */ readPaths: envPathList, writePaths: envPathList, denyPaths: envPathList, readOnly: envBoolean.default(false), /** Opt-in delete confirmation round; when true and writes are allowed, HTTP requires a stateful session. */ deleteElicitation: envBoolean.default(false), omnisearchUrl: z.string().url().optional(), }); let _config: z.infer | undefined; export function getServerConfig() { _config ??= parseEnvConfig(ServerConfigSchema, { apiKey: 'OBSIDIAN_API_KEY', baseUrl: 'OBSIDIAN_BASE_URL', verifySsl: 'OBSIDIAN_VERIFY_SSL', requestTimeoutMs: 'OBSIDIAN_REQUEST_TIMEOUT_MS', enableCommands: 'OBSIDIAN_ENABLE_COMMANDS', readPaths: 'OBSIDIAN_READ_PATHS', writePaths: 'OBSIDIAN_WRITE_PATHS', denyPaths: 'OBSIDIAN_DENY_PATHS', readOnly: 'OBSIDIAN_READ_ONLY', deleteElicitation: 'OBSIDIAN_DELETE_ELICITATION', omnisearchUrl: 'OBSIDIAN_OMNISEARCH_URL', }); return _config; } ``` `parseEnvConfig` maps Zod schema paths → env var names so validation errors name the actual variable (`OBSIDIAN_API_KEY`) rather than the internal path (`apiKey`). It throws a `ConfigurationError` the framework catches and prints as a clean startup banner. ### Session posture and shutdown `src/index.ts` passes two `createApp()` options that shape how the server runs: ```ts const deleteGateActive = config.deleteElicitation && !config.readOnly; await createApp({ // ... sessionMode: deleteGateActive ? { default: 'stateful', require: 'stateful' } : { default: 'stateful' }, teardown: () => obsidian.close(), }); ``` Unset, `MCP_SESSION_MODE` runs `stateful`. With `OBSIDIAN_DELETE_ELICITATION=true`, `sessionMode` declares a requirement, not just a default: `obsidian_delete_note` then confirms through `ctx.requestInput`, which a 2025-era HTTP client can only answer on a stateful session, so under stateless HTTP the tool would be unusable for those clients. In that mode, when the resolved HTTP mode is `stateless` (an explicit `MCP_SESSION_MODE=stateless`), startup fails with a `ConfigurationError` naming the conflict. With the confirmation off (the default), or with `OBSIDIAN_READ_ONLY=true` (which disables `obsidian_delete_note`, so no round can run), nothing needs a session and stateless HTTP starts. stdio is never refused — `MCP_SESSION_MODE` has no effect there. `tests/integration/delete-note-confirmation.test.ts` pins each case. The startup "Path policy" log line reports `deleteElicitation` as `deleteGateActive` — false under read-only, as `enableCommands` is. The delete confirmation's consent records (on mode only) live in `ctx.state`, backed by the framework storage provider (`STORAGE_PROVIDER_TYPE`, default `in-memory`, process-local). That holds for stdio and for a single stateful HTTP instance, where every round of a confirmation reaches the process that asked. A multi-instance deployment, where a retry can land on another instance, needs a shared provider — `filesystem`, `supabase`, or `cloudflare-d1`, never `cloudflare-kv` (eventually consistent, so a record may be unseen or outlive its redemption). Redemption is single-use against a sequential replay but not against concurrent retries until the framework has an atomic `ctx.state.take` (cyanheads/mcp-ts-core#593). `teardown` closes the undici `Agent` dispatcher `ObsidianService` holds for the Local REST API and Omnisearch, releasing its keep-alive sockets, and disposes the note-body read queue, rejecting reads still waiting. It runs after the transport stops accepting requests, on every shutdown path. --- ## Context Handlers receive a unified `ctx` object. Properties this server actually uses: | Property | Description | |:---------|:------------| | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. | | `ctx.requestInput` / `ctx.inputs` | Multi-round-trip human-in-the-loop confirmation. Always present, both protocol eras — with `OBSIDIAN_DELETE_ELICITATION=true`, `obsidian_delete_note` requests a confirmation round before the DELETE; off, it reads neither. `requestInput` returns `never`, so write it in return position. | | `ctx.state` | Tenant-scoped KV. Used only for `obsidian_delete_note`'s consent records (`consent/`, 600 s TTL), written only with `OBSIDIAN_DELETE_ELICITATION=true` — see Session posture above for provider requirements. | | `ctx.auth` | Caller identity (`clientId`, `sub`) bound into each consent record; absent on stdio and `MCP_AUTH_MODE=none`, where the record carries empty strings. | | `ctx.signal` | `AbortSignal` propagated to the Local REST API client so client cancellations cut off in-flight HTTP; the request timer and the call budget join it per attempt. | | `ctx.requestId` | Unique request ID — surfaces in log lines for correlation. | | `ctx.tenantId` | Tenant ID from JWT or `'default'` for stdio. | See the framework `CLAUDE.md` for the full surface. --- ## Errors Handlers throw — the framework catches, classifies, and formats. **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable?, severity?, thrownBy? }]` on `tool()` / `resource()` to receive `ctx.fail(reason, …)` typed against the reason union. TypeScript catches typos at compile time, `data.reason` is auto-populated for observability, linter enforces conformance against the handler body. `recovery` is required (≥ 5 words, lint-validated) — the single source of truth for the agent's next move. The framework puts it on the wire whenever a failure carrying that `reason` arrives without a hint — a bare `ctx.fail('reason')` or a service throw with `data: { reason }` — as `data.recovery.hint`, mirrored into `content[]` text unless the message already contains it verbatim; override with an explicit `{ recovery: { hint: '...' } }` when dynamic runtime context matters. Every error envelope also carries `data.requestId`, the id the server's log records for that call carry, and `content[]` closes with `(reason … · request )`. Mark an entry the service layer throws with `thrownBy: 'service'` so `error-contract-unthrown` skips it — lint-only metadata, nothing at runtime reads it. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely and don't need declaring. ```ts errors: [ { reason: 'note_missing', code: JsonRpcErrorCode.NotFound, when: 'No note matched the path', recovery: 'Verify the path with obsidian_list_notes or use obsidian_search_notes to locate the note.' }, { reason: 'plugin_unreachable', code: JsonRpcErrorCode.ServiceUnavailable, when: 'Local REST API plugin is offline', retryable: true, recovery: 'Confirm Obsidian is running with the Local REST API plugin enabled.' }, ], async handler(input, ctx) { const note = await svc.getNote(input.path, ctx); // Static recovery — the framework fills the contract's hint onto the wire. if (!note) throw ctx.fail('note_missing', `Note ${input.path} not found`); return note; } ``` **Declare contracts inline on each tool, even when they look similar across tools.** The contract is part of the tool's documented public surface — reading one tool definition file should give the full picture (input, output, errors, handler, format). Don't extract a shared `errors[]` constant or contract module to deduplicate; per-tool repetition is the intended cost of locality, and dynamic `recovery` hints often need tool-specific context anyway. Service-side throws carry only `data.reason`; the tool and resource handler factories fill the calling definition's contract recovery from it, so `#throwForStatus` sets the reason per status branch and nothing else: ```ts // inside obsidian-service.ts throw notFound(`Not found: ${display}`, data('note_missing'), { cause }); // where data(reason) does: { ...callerIdentifier(path), reason } // — `path` on a note route, `commandId` on /commands//, no key on routes // that carry no caller input (/, /tags/, /commands/, /search/). // The upstream body is never spread into `data` — it rides as `cause`, which // is non-enumerable and so reaches the log without reaching the client. ``` An attempt (`#send`) is the fetch and the body read together, run under a timer of `OBSIDIAN_REQUEST_TIMEOUT_MS` joined to the request's signal, the one clock both runtimes honor (Bun ignores the undici `Agent`'s timeouts, which are off). GET/PUT/DELETE retry through `withRetry`, and every request one call makes — each attempt, each backoff, each request the handler chains — shares one budget, `CALL_DEADLINE_MS` (45 s) or the timeout when that is longer, anchored per `Context` on the call's first request, so a stalled or slow plugin settles inside the 60 s an MCP client waits. A rejection is classified inside the attempt, so the retry decision sees the typed error: a refused certificate throws `ConfigurationError` `certificate_rejected` on the first attempt; an unreachable plugin, or a connection dropped mid-body, throws `ServiceUnavailable` `obsidian_unreachable` and keeps the GET/PUT/DELETE retries; the timer or the budget running out throws `Timeout` `obsidian_timeout` (a `retry_deadline_exceeded` from `withRetry` is rethrown as `obsidian_timeout`, attempt count kept, unless the last attempt failed some other typed way, which then surfaces as it is). The timer is matched by its own abort reason, never by the `TimeoutError` name, so a caller's cancellation and a scoped search's deadline pass through untouched and are never retried; a scoped search's requests take its 45 s deadline as their budget instead of the call's, so the search still fails `*_too_costly`. All three carry an inline `recovery.hint` rather than relying on the contract fill, because they reach every tool and resource — including resources with no `errors[]` — and the operator, not the agent, fixes them. **Fallback for ad-hoc throws** (no contract entry fits, prototype tools, service-layer code without a contract): use error factories. ```ts import { notFound, validationError, serviceUnavailable } from '@cyanheads/mcp-ts-core/errors'; throw notFound('Note not found', { path }); throw serviceUnavailable('Local REST API unavailable', { url }, { cause: err }); ``` Local REST API responses never go through `httpErrorFromResponse`. `#throwForStatus` reads the body (already in memory from the attempt) only to pick a reason per status branch, keeps the upstream text on `cause`, and maps every other 4xx/5xx with `httpStatusToErrorCode`, re-attaching only `retryAfter` and a 501's `retryable: false`. The helper would put the upstream's reason phrase in the message and `data.statusText`, which the containment invariant keeps off the wire. Available factories: `notFound`, `validationError`, `forbidden`, `unauthorized`, `invalidParams`, `invalidRequest`, `conflict`, `rateLimited`, `timeout`, `serviceUnavailable`, `configurationError`, `internalError`, `serializationError`, `databaseError`. Plain `Error` is also auto-classified from message patterns (`'not found'` → `NotFound`, etc.). See framework CLAUDE.md and the `api-errors` skill for the full pattern table. --- ## Structure ```text src/ index.ts # createApp() entry point — registers tools/resources, inits Obsidian service instructions.ts # buildInstructions() — server `instructions`, effective path scope included config/ server-config.ts # OBSIDIAN_* env vars (Zod schema) services/ obsidian/ obsidian-service.ts # Local REST API client (init/accessor pattern) path-policy.ts # PathPolicy — OBSIDIAN_READ_PATHS / WRITE_PATHS / DENY_PATHS / READ_ONLY gate jsonlogic-deps.d.ts # Type declarations for json-logic-js and glob-to-regexp jsonlogic-evaluator.ts # Scoped JSONLogic evaluation: bounds, worker hand-off, logic_* errors jsonlogic-worker.ts # Worker entry: the plugin's JSONLogic operators, hardened and budgeted simple-search.ts # In-server port of the plugin's /search/simple/ matching, for text search under a read scope frontmatter-ops.ts # YAML frontmatter parse/serialize/edit helpers + inline tag reader + the wikilink span rule (`wikilinkCloser`) `obsidian_get_note` imports markdown-blocks.ts # Block structure (code, HTML, math, tables) for inline tag detection patch-instruction.ts # markdown-patch 1.x headers / 2.0 instructions, format negotiation, 2.0 map flattening section-extractor.ts # Heading/block/frontmatter section extraction + the repeated-link-definition guard for heading writes (`droppedDefinitionInReach`) types.ts # Domain types (NoteJson, NoteTarget, PathTarget, etc.) mcp-server/ tools/definitions/ _shared/schemas.ts # Shared TargetSchema + SectionSchema reused across tools _shared/suggest-paths.ts # Case-mismatch fallback and suggestions for reads; names the existing note on a `case_variant_exists` write index.ts # read/write/command tool sets + buildSearchNotesTool (Omnisearch-aware) and buildDeleteNoteTool (elicitation mode) factories obsidian-*.tool.ts # 14 tool definitions (12 base + 2 opt-in command-palette pair) resources/definitions/ index.ts # allResourceDefinitions[] obsidian-vault-note.resource.ts # obsidian://vault/{+path} obsidian-tags.resource.ts # obsidian://tags obsidian-status.resource.ts # obsidian://status prompts/definitions/ index.ts # allPromptDefinitions = [] (intentionally empty) skills/ obsidian-guide/SKILL.md # Published skill: gates and multi-call workflows, served as skill://obsidian-guide/SKILL.md ``` --- ## Naming | What | Convention | Example | |:-----|:-----------|:--------| | Files | kebab-case with suffix | `search-docs.tool.ts` | | Tool/resource/prompt names | snake_case | `search_docs` | | Directories | kebab-case | `src/services/doc-search/` | | Descriptions | Single string or template literal, no `+` concatenation | `'Search items by query and filter.'` | --- ## Skills Two skill trees can live at the project root, written for different readers: | Tree | For | Written by | |:-----|:----|:-----------| | `framework-skills/` | The agent developing this server — framework skills (`metadata.audience: external`) plus any development-time skills of the server's own | `init` and the `maintenance` sync (framework skills); you (your own) | | `skills/` | The agents that install the server and call its tools — tool chains, identifier sources, gates | You, deliberately, with the `add-skill` skill. Here: `obsidian-guide`, served through `createApp({ skills: 'skills' })` | Development skills are modular instructions. Read them directly when a task matches — e.g., `framework-skills/add-tool/SKILL.md` when adding a tool. `bun run list-skills` prints the full registry. Their directory is deliberately not `skills/`: Claude Code and Codex auto-load a plugin's root `skills/`, so a server that ships `.claude-plugin/` or `.codex-plugin/` would hand them to every agent that installs it. A published skill in root `skills/` reaches plugin installs and the `.mcpb` bundle as-is, ships in the npm package and the Docker image (`package.json` `files` and the Dockerfile already carry `skills/`), and reaches MCP clients when the server opts in with `createApp({ skills: 'skills' })`. `lint:packaging` validates the tree. **Agent skill directory:** Copy `framework-skills/` into the directory your agent discovers (Claude Code: `.claude/skills/`, others: equivalent). Skills then load as context without referencing `framework-skills/` paths. After framework updates, run the `maintenance` skill — Phase B re-syncs the agent directory. Available skills: | Skill | Purpose | |:------|:--------| | `setup` | Post-init project orientation | | `design-mcp-server` | Design tool surface, resources, and services for a new server | | `add-tool` | Scaffold a new tool definition | | `add-app-tool` | Scaffold an MCP App tool + paired UI resource | | `add-resource` | Scaffold a new resource definition | | `add-prompt` | Scaffold a new prompt definition | | `add-service` | Scaffold a new service integration | | `add-test` | Scaffold test file for a tool, resource, or service | | `add-skill` | Author a skill the server publishes in root `skills/` for the agents that use it — when one earns its place, structure, validation, delivery | | `field-test` | Exercise tools/resources/prompts with real inputs, verify behavior, report issues | | `security-pass` | Audit server for MCP-flavored security gaps: output injection, scope blast radius, input sinks, tenant isolation | | `tool-defs-analysis` | Read-only audit of MCP definition language across the surface — voice, leaks, defaults, recovery hints, output descriptions | | `code-simplifier` | Post-session cleanup against `git diff` — modernize syntax, consolidate duplication, align with the codebase | | `polish-docs-meta` | Finalize docs, README, metadata, and agent protocol for shipping | | `git-wrapup` | Land working-tree changes as a commit stack — version bump, changelog, verify, commit by concern, release commit on top. No tag, no push to main; opens the release PR when the project declares release PR mode | | `release-pr-review` | Review pass on an open release PR — simplifier + correctness review, fixes as ordinary commits on top of the stack, PR body kept in sync. Release PR mode only | | `release-and-publish` | Fast-forward merge (release PR mode) + tag + push + npm + MCP Registry + GH Release + Docker. Picks up from `git-wrapup` | | `maintenance` | Investigate changelogs, adopt upstream changes, sync skills to agent dirs | | `orchestrations` | Chain task skills into a gated multi-phase pipeline — build-out, QA-fix, update-ship — when you can spawn sub-agents | | `report-issue-framework` | File a bug or feature request against `@cyanheads/mcp-ts-core` via `gh` CLI | | `report-issue-local` | File a bug or feature request against this server's own repo via `gh` CLI | | `techniques` | Catalog of response/data-shaping techniques — overflow handling, payload shaping, retrieval patterns | | `api-auth` | Auth modes, scopes, JWT/OAuth | | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in | | `api-config` | AppConfig, parseConfig, env vars | | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input | | `api-errors` | McpError, JsonRpcErrorCode, error patterns | | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` | | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in | | `api-services` | LLM, Speech, Graph services | | `api-telemetry` | OTel catalog: spans, metrics, completion logs, env config, cardinality rules | | `api-testing` | createMockContext, test patterns | | `api-utils` | Formatting, parsing, security, pagination, scheduling, telemetry helpers | | `api-workers` | Cloudflare Workers runtime | **Chaining skills into pipelines.** When the user wants a multi-phase effort — build this server out, QA-and-fix the surface, update-and-ship — *and you can spawn sub-agents*, `framework-skills/orchestrations/SKILL.md` sequences the task skills above into a gated pipeline with verification at each step. Read it to drive the run. Optional: skip it if you can't orchestrate sub-agents, and ignore it entirely if you were *spawned* as one — you've already been scoped to a single phase. When you complete a skill's checklist, check the boxes and add a completion timestamp at the end (e.g., `Completed: 2026-03-11`). --- ## Commands **Runtime:** Scripts use Bun's native TypeScript execution — `bun run ` is the standard invocation. `npm run ` also works (npm delegates to bun). | Command | Purpose | |:--------|:--------| | `bun run build` | Compile TypeScript | | `bun run rebuild` | Clean + build | | `bun run clean` | Remove build artifacts | | `bun run devcheck` | Lint + format + typecheck + security + changelog sync | | `bun run audit:fix` | `bun audit fix` — upgrade vulnerable packages to the lowest safe version within existing ranges (`--dry-run` previews, `--latest` rewrites ranges). First response when `devcheck` flags a transitive advisory; then `bun update `, then `bun dedupe` | | `bun run audit:refresh` | Delete `bun.lock` and reinstall. Last resort after `audit:fix`, `bun update `, and `bun dedupe` — re-resolves every ranged dep (the framework pin included) and rewrites the lockfile as `lockfileVersion: 2` | | `bun run tree` | Generate `docs/tree.md` | | `bun run list-skills` | Print project skill index (name, version, description) | | `bun run format` | Auto-fix formatting (safe fixes only) | | `bun run format:unsafe` | Also apply Biome's unsafe autofixes — review the diff; they can change behavior | | `bun run lint:mcp` | Validate MCP definitions against the linter rules | | `bun run lint:packaging` | Packaging surface checks — `server.json`/`manifest.json` env-var parity, `user_config` wiring, `.mcpbignore` coverage, plugin manifest identity and env contract, the published `skills/` tree (run by devcheck) | | `bun run bundle` | Build, pack, and clean a `.mcpb` for one-click Claude Desktop install | | `bun run test` | Run tests (Vitest — use `bun run test`, not `bun test`) | | `bun run test:coverage` | Run tests with Istanbul coverage | | `bun run start:stdio` | Production mode (stdio) — requires `bun run build` first | | `bun run start:http` | Production mode (HTTP) — requires `bun run build` first | | `bun run changelog:build` | Regenerate `CHANGELOG.md` rollup from `changelog/.x/*.md` | | `bun run changelog:check` | Verify `CHANGELOG.md` is in sync (used by devcheck) | **CI is one file.** `.github/workflows/codeql.yml` is the only GitHub Actions workflow: CodeQL is GitHub-owned end to end, and the file runs only while the repo's CodeQL *default setup* is turned off. Verification — `devcheck`, tests, the release gates — runs locally; don't add a workflow that re-runs it. --- ## Bundling `bun run bundle` produces a `.mcpb` extension bundle for one-click install in Claude Desktop. `mcpb pack` reads `.mcpbignore`, not `.gitignore`, so every root path the bundle must not ship — source, tests, docs, caches, logs, agent docs, plugin manifests, gitignored local files — needs a root-anchored line there (`/docs/`, never `docs/`, which also strips `node_modules/*/docs/`); `lint:packaging` names each missing or unanchored line. Root `skills/` ships on purpose. The pack step is followed by `scripts/clean-mcpb.ts`, which prunes dev dependencies (`mcpb clean`) and strips four classes of `node_modules/**` content that root-anchored `.mcpbignore` patterns cannot reach: dependency-shipped agent docs — `framework-skills/`, `skills/`, `.claude/`, `.agents/`, `AGENTS.md`, and `CLAUDE.md` at a package's root, and `SKILL.md` anywhere (a `skills/` deeper in a package, such as the MCP SDK's `dist/ext/skills/`, is runtime code and stays); platform-specific native bindings, which would otherwise lock the bundle to the platform it was packed on; node-gyp build output beside a `binding.gyp`, which records the packing machine's paths (compiled `*.node` addons stay); and build-only package files — the framework's `changelog/`, `scripts/`, `templates/`, and config bases. MCPB is stdio-only — HTTP deployments are unaffected. Delete `manifest.json` and `.mcpbignore` if not shipping MCPB bundles; `lint:packaging` skips cleanly. **Adding an env var requires both files:** `server.json` (registry discovery, `environmentVariables[]`) and `manifest.json` (bundle install UX, `mcp_config.env` + `user_config`). `lint:packaging` (run by `devcheck`) verifies the env var names match, that every `user_config` option is wired into `mcp_config.env` as `"X": "${user_config.X}"` (the host substitutes nothing else — `"${X}"` reaches the server as that literal string), and that an optional string option carries `"default": ""`. A user-supplied variable also goes into the plugin manifests: `.claude-plugin/plugin.json` `userConfig` + `${user_config.