Skip to main content

Command Palette

Search for a command to run...

Only One Crosses the Bridge at a Time > Heimdall MCP Adds Resource Locks

Updated
9 min readView as Markdown
Only One Crosses the Bridge at a Time > Heimdall MCP Adds Resource Locks
E

I am a computer science engineer, I have also been a member of CERN’s Summer Students program in 2022. I am constantly learning and reviewing new web development technologies Frontend, Backend, DevOps

The race that nobody warns you about

Run two Claude Code sessions against the same repo — one refactoring a module, one fixing a typo three files away that happens to also touch a shared config file — and eventually both sessions decide to write the same file within a few hundred milliseconds of each other. Nothing stops that. The second write wins, silently. The first agent's changes are gone, and neither session has any idea it happened.

The same thing happens one layer down, with MCP servers instead of native editor tools: an MCP filesystem server invoked by two agent processes, or a run_migration tool exposed by a database server, called twice in close succession by two unrelated sessions. Heimdall MCP already had tool-name policies (v1.2) and argument-level policies (v1.4) — you could say "never call write_file on /etc/passwd" — but neither of those answers a different question: what happens when two calls to the same resource land at the same time?

That's the failure mode 1.5.0 is built to close.

Repo: https://github.com/enmanuelmag/heimdall-mcp Website: https://stack.cardor.dev/heimdall

What shipped

Version 1.5.0 adds resource locks, enforced at two levels that share the same underlying mechanism: MCP tool calls routed through Heimdall's proxy, and host-native tools (Claude Code's Write/Edit/MultiEdit/NotebookEdit, and OpenCode's equivalent) that never touch the proxy at all.

Layer 1: locks on MCP servers

A locks block, keyed by tool name, sits alongside a server's existing tools and toolPolicies config:

// heimdall.config.ts
export default {
  servers: {
    filesystem: {
      tools: { allow: ['read_file', 'write_file'] },
      locks: {
        write_file: { resource: 'path', ttl: 30_000 },
        run_migration: { resource: 'db-migration', onConflict: 'warn' },
      },
    },
  },
} satisfies HeimdallConfig;

Each entry is a LockRule:

Field Type Default Description
resource string Name of a tool-call argument whose value becomes the lock key (e.g. resource: 'path' locks on arguments.path), or a literal key (e.g. 'db-migration') if no argument by that name exists. Falls back to the tool name if omitted. Path-like values are canonicalized automatically.
ttl number 30000 Lock time-to-live in milliseconds — a backstop so a crashed or hung holder can't lock a resource forever.
onConflict 'reject' | 'warn' 'reject' reject blocks the call and returns a RESOURCE_LOCKED JSON-RPC error. warn forwards the call anyway and attaches lock.* metadata to the OTel span instead of blocking.

write_file locking on path means two calls to write_file with the same path serialize; two calls with different paths never contend. run_migration locking on the literal key db-migration means every call to that tool serializes against every other call, regardless of arguments — useful when the resource being protected isn't any single argument, it's "the database."

Layer 2: locks on host-native tools

MCP servers only cover part of an agent's surface area. Claude Code's own file-editing tools — Write, Edit, MultiEdit, NotebookEdit — are built into the coding agent itself. They're never MCP servers, so they never pass through Heimdall's JSON-RPC proxy, and no policy layer that hooks into tools/call can see them.

1.5.0 adds a hosts field, a sibling of servers/default, that applies the exact same LockRule shape to these native tools:

// heimdall.config.ts
export default {
  hosts: {
    'claude-code': {
      locks: {
        Write: { resource: 'file_path', ttl: 30_000 },
        Edit: { resource: 'file_path', ttl: 30_000 },
        MultiEdit: { resource: 'file_path', ttl: 30_000 },
        NotebookEdit: { resource: 'file_path', ttl: 30_000 },
      },
    },
  },
} satisfies HeimdallConfig;

@cardor/heimdall-mcp exports CLAUDE_CODE_DEFAULT_HOST_POLICY — exactly this policy — applied automatically as a baseline whenever neither your local nor global config sets hosts['claude-code']. You don't have to write it yourself to get the protection; you only write it if you want to change it.

Why Bash is excluded. An arbitrary shell command has no single stable "resource" argument. It might touch zero files, one file, or a dozen. Locking on the command string would be meaningless; locking Bash calls globally would serialize unrelated work for no reason. So Bash has no lock rule in the default policy, and none is recommended.

Technical deep dive

How Claude Code enforcement actually works

There's no proxy in the loop for native tools, so this required a genuinely different enforcement path: bin/hooks/claude-pretooluse.js, a real PreToolUse hook script. On every invocation it:

  1. Reads tool_name / tool_input from stdin
  2. Reloads heimdall.config.* fresh from disk — local and global, merged — never cached
  3. Matches the tool against hosts['claude-code'].locks
  4. Resolves the lock resource from the matched rule's argument
  5. Attempts to acquire an exclusive lock against the same SQLite lock store the proxy itself uses (~/.config/heimdall/locks.db by default)

If the resource is free, the call proceeds. If it's held, the call is denied with a human-readable reason. Critically, the hook fails open: any unexpected internal error results in exit code 0 (allow), never a hard block — a bug in the hook must never brick a Claude Code session.

Register it with:

heimdall-mcp init --hooks claude-code

This reads (or creates) ~/.claude/settings.json, resolves the absolute path to the installed package's hook script, and appends a PreToolUse entry — without touching any other hooks.* entries or unrelated settings keys. It's idempotent: running it twice makes no changes the second time, and the write is atomic (temp-file-then-rename), so the settings file is never left partially written.

OpenCode: an in-process plugin, and an honest caveat

OpenCode's equivalent, bin/plugins/opencode-heimdall.js, follows the same config-loading and lock-acquisition logic but is architecturally different: instead of a subprocess spawned per call over stdin/stdout, OpenCode resolves the plugin once via import() at startup and it runs in-process, matched against hosts['opencode'] for the rest of the session.

There is no built-in default policy for OpenCode yet — no OPENCODE_DEFAULT_HOST_POLICY — so calls are allowed until you configure hosts.opencode.locks explicitly:

hosts: {
  opencode: {
    locks: {
      write: { resource: 'filePath', ttl: 30_000 },
    },
  },
},

heimdall-mcp init --hooks opencode registers it into ~/.config/opencode/opencode.jsonc's plugin array, using jsonc-parser (the same library VS Code uses internally) to make a surgical text edit rather than a JSON.parse/stringify round trip — so existing comments and formatting elsewhere in the file survive untouched.

Here's the part worth saying plainly rather than glossing over: the plugin denies a conflicting lock by throwing an Error from the hook callback, on the assumption that a thrown error aborts the tool call — a reasonable assumption for a void-returning before-hook, and nothing found while researching OpenCode's source contradicts it, but it has not been confirmed against a live OpenCode session. Same caveat applies to the init --hooks opencode registration path itself — verified with high confidence against OpenCode's fetched source and the installed binary's embedded strings, but not validated end-to-end against a real running OpenCode process actually loading the plugin. Both are documented as experimental until independently verified, not shipped as if they were fully proven.

What a lock conflict looks like

A rejected tools/call returns a distinct error code with structured holder info:

{
  "jsonrpc": "2.0",
  "id": 42,
  "error": {
    "code": -32600,
    "message": "Resource '/repo/file.txt' is locked (requested by tool 'write_file')",
    "data": {
      "resource_key": "/repo/file.txt",
      "held_by": "a1b2c3d4...",
      "expires_at": 1735689600000
    }
  }
}

-32600 is exported as RESOURCE_LOCKED. onConflict: 'warn' skips the block entirely and forwards the call, attaching lock.conflict_warning, lock.resource_key, and lock.held_by to the OTel span instead — useful for observing contention before deciding to enforce it.

Path canonicalization and the lock store

Resource keys that look like filesystem paths — absolute, ~-prefixed, relative (./, ../), or a Windows drive letter — are canonicalized via fs.realpathSync before being used as a lock key. That means the same real file locks consistently whether it's referenced by a relative path from one project directory, an absolute path, or a symlink pointing at it from somewhere else.

The default lock store is a local SQLite file at ~/.config/heimdall/locks.db — zero configuration required, and it's the same store used by the Claude Code hook, the OpenCode plugin, and the proxy's own LockInterceptor. For multi-machine coordination — multiple proxy instances, or a fleet of agents on different hosts sharing the same underlying resources — Postgres and MySQL backends are available:

heimdall-mcp --store sqlite://./traces.db --lock-store postgres://user:pass@host/db -- node server.js

Limitations — stated plainly

  • No read-mode locking. Every lock is acquired in exclusive 'write' mode. The storage interface defines LockMode = 'read' | 'write', but LockRuleSchema has no mode field yet, and LockInterceptor hardcodes 'write' on every acquisition. Two calls that are conceptually read-only still serialize against each other if they share a lock rule.
  • No lock support for Bash. By design — no stable resource argument to lock on.
  • No automatic release on tool completion. Neither the Claude Code hook nor the OpenCode plugin has a companion hook (PostToolUse / tool.execute.after) to release the lock immediately when the call finishes. Release happens only via TTL expiration (default 30s) — not a bug, a known gap.
  • OpenCode's deny mechanism and init --hooks opencode registration are unverified end-to-end against a live OpenCode process, as described above.

TTL itself deserves one more sentence: it's a backstop for crashed or hung holders, not a per-call timeout. If a process holding a lock dies before releasing it, the lock would otherwise block that resource forever; once the TTL elapses, a new caller can acquire it. Release is idempotent — if the original holder later calls release after its lock already expired and was reacquired by someone else, that stale release is a silent no-op.

Getting 1.5.0

npm install -g @cardor/heimdall-mcp
heimdall-mcp init --hooks claude-code
heimdall-mcp init --hooks opencode

Built by @enmanuelmag for @cardor. Feedback and issues welcome on GitHub.