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

> Source: <https://dev.to/enmanuelmag/only-one-crosses-the-bridge-at-a-time-heimdall-mcp-adds-resource-locks-4mm5>
> Published: 2026-07-16 01:19:52+00:00

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](https://github.com/enmanuelmag/heimdall-mcp)

Website: [https://stack.cardor.dev/heimdall](https://stack.cardor.dev/heimdall)

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.

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'` |

`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."

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.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:

`tool_name`

/ `tool_input`

from stdin`heimdall.config.*`

fresh from disk — local and global, merged — never cached`hosts['claude-code'].locks`

`~/.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'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

`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.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.

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
```

`'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.`Bash`

.`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.`init --hooks opencode`

registration are unverified end-to-endTTL 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.

```
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.*
