Agents

Make every coding agent use Skuld

Connect the Skuld MCP, paste the rules, add the hook. From then on every pull request your agent opens comes with the change drawn as flows, the agent's own explanation, and one question for you: ready to merge?

Set it up in three steps

Your agent
  1. 1. Connect

    Create a token on the Agent tokens page and export it as SKULD_TOKEN on the machine that runs your agent. Every snippet here reads it from the environment, so the token never sits in a file.

    in a terminal
    export SKULD_TOKEN=<paste the token here>
    run once in a terminal
    claude mcp add --transport http skuld https://skuldai.com/mcp --header "Authorization: Bearer $SKULD_TOKEN"

    In a terminal, in the repository folder you have open in Claude Code, with SKULD_TOKEN exported there. This is the Claude Code CLI; claude.ai in the browser is a different app. Then run claude mcp list and check that skuld is there.

  2. 2. Paste the rules

    Paste the section into AGENTS.md at the repository root. Claude Code reads CLAUDE.md: paste it there instead, or give CLAUDE.md one line, Read and follow AGENTS.md.

    AGENTS.md
    ## Skuld: every pull request
    
    - Keep each PR to one flow, or a small group of flows joined by the knots (actions) they share.
    - Before you code, list the flows you plan to touch. More than 2 flows: say why, or propose a split (the shared knot first, then one PR per flow group) and ask.
    - After `get_change`, call `check_scope` and use its `line` as the "Scope:" line of the summary. Call it with `ref` too, before you open a PR for a branch you pushed.
    - On Wide or Sprawling: tell the human and offer the split it returns. It never blocks: do not stop because of it, and never split without asking.
    - Separate refactors from behaviour changes. Keep a flow's tests in the same PR.
    - After you open a PR or push to it: `get_change`, `check_scope`, `explain_change` (bound to the head sha), `render_change_image`. Put the `markdown` it returns (Skuld link, guide, explanation) in the PR body.
    - Then post the summary in chat, using this template:
    
      ```text
      PR #<n> · <title> · <url>
      [the Skuld change image]
      Scope: <F> flows (<names>), <K> steps, <R> removed, reach <N> · <Focused|Wide|Sprawling>
      What changed: <the guide steps>
      Why: <the explanation>
      Tests: server p/f/s · web p/f/s · monitor p/f/s (passed/failed/skipped)
      Findings: <new errors, or none>
      Ready to merge? Reply "merge" and I'll merge as is. I won't merge without it.
      ```
    
    - Then stop. Never merge, approve, or turn on auto-merge without an explicit "merge" from the owner in this conversation.
    - If the Skuld MCP is not connected, say so in the summary and still ask. Do not skip the ask.
  3. 3. Add the hook

    A rules file asks. A hook reminds: it runs after the agent opens a pull request or pushes, and once more when the agent is about to stop with the steps unfinished.

    Copy both files into the repository. .claude/settings.json has one permission rule (ask on gh pr merge, so every merge needs your click) and five hooks that run the script: after gh pr create, after a create_pull_request MCP tool, after git push, after render_change_image, and when the agent is about to stop. With a pull request still open in the session, the stop hook blocks once and names the missing steps. If you already have a settings file, merge the keys into it. SKULD_PR_HOOKS=off turns the script off.

    .claude/settings.json
    {
      "permissions": {
        "ask": ["Bash(gh pr merge *)"]
      },
      "hooks": {
        "PostToolUse": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "if": "Bash(gh pr create *)",
                "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/skuld-pr.mjs\" after-pr",
                "timeout": 10
              }
            ]
          },
          {
            "matcher": "mcp__.*__create_pull_request",
            "hooks": [
              {
                "type": "command",
                "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/skuld-pr.mjs\" after-pr",
                "timeout": 10
              }
            ]
          },
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "if": "Bash(git push *)",
                "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/skuld-pr.mjs\" after-push",
                "timeout": 10
              }
            ]
          },
          {
            "matcher": "mcp__.*__render_change_image",
            "hooks": [
              {
                "type": "command",
                "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/skuld-pr.mjs\" done",
                "timeout": 10
              }
            ]
          }
        ],
        "Stop": [
          {
            "hooks": [
              {
                "type": "command",
                "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/skuld-pr.mjs\" stop",
                "timeout": 10
              }
            ]
          }
        ]
      }
    }
    .claude/hooks/skuld-pr.mjs
    #!/usr/bin/env node
    /**
     * Hooks for the Skuld PR workflow (the rules "Skuld: every pull request"; docs/agent-pr-workflow.md,
     * https://skuldai.com/agents). One script for three agents:
     *
     *   node skuld-pr.mjs <mode> [--agent claude|cursor|kiro]
     *
     *   mode: after-pr | after-push | done | stop     one hook each (Claude Code picks them with matchers)
     *         after-shell                             after any shell command: `gh pr create` is after-pr,
     *                                                 `git push` is after-push, anything else is nothing
     *         after-mcp                               after any MCP tool: create_pull_request is after-pr,
     *                                                 render_change_image is done, anything else is nothing
     *
     * --agent (default claude) says whose hook JSON is on stdin and how to answer:
     *   claude  session_id, tool_response. Context: { hookSpecificOutput: { additionalContext } }.
     *           Stop: stop_hook_active, answers { decision: "block", reason }. Tested.
     *   cursor  conversation_id; afterShellExecution has command and output, afterMCPExecution has tool_name and
     *           result_json. The docs name no output for these two, so the PR is only recorded and nothing is
     *           printed. stop: loop_count, answers { followup_message }.
     *   kiro    session_id, tool_name, tool_input. The docs do not name the field that holds a tool's result, so the
     *           whole hook input is searched for the PR URL. The stdout of a hook that exits 0 is added to the
     *           agent's context, so the steps are printed as plain text. Stop answers { decision: "block", reason }.
     * Cursor and Kiro follow their docs and are not tested against the real agents yet.
     *
     * Plain Node, no dependencies, no network. It reads two env names only (SKULD_PR_HOOKS, TMPDIR) and never prints
     * an env value. The state of a session is one small file under <TMPDIR or /tmp>/skuld-pr-hooks/, never in the
     * repository.
     *
     * It fails open: on any error (bad JSON, unreadable state, unknown mode or agent) it exits 0 with no output, so
     * a hook can never break a session. A reminder, not a security boundary: a person still merges.
     */
    import fs from 'node:fs';
    import path from 'node:path';
    
    const MAX_OUTPUT = 2000;
    const MAX_SCAN = 200_000;
    const PR_URL = /https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/(\d+)/;
    const SECTION = '"Skuld: every pull request"';
    /** Where each agent keeps the rules, as the reminders name it. */
    const RULES_FILE = { claude: 'AGENTS.md', cursor: 'AGENTS.md or .cursor/rules/skuld.mdc', kiro: 'AGENTS.md or .kiro/steering/skuld.md' };
    const PR_CREATE = /\bgh\s+pr\s+create\b/;
    const GIT_PUSH = /\bgit\s+push\b/;
    
    function readStdin() {
        return new Promise((resolve, reject) => {
            let text = '';
            process.stdin.setEncoding('utf8');
            process.stdin.on('data', (chunk) => { text += chunk; });
            process.stdin.on('end', () => resolve(text));
            process.stdin.on('error', reject);
        });
    }
    
    /** A tool response as text: a string, a `{ stdout }` object or an MCP content array. Never throws. */
    function textOf(value) {
        try {
            const text = typeof value === 'string' ? value : JSON.stringify(value) ?? '';
            return text.slice(0, MAX_SCAN);
        } catch {
            return '';
        }
    }
    
    /** `--agent <name>`: claude when the flag is absent, null (fail open) for a name this script does not know. */
    function agentOf(argv) {
        const at = argv.indexOf('--agent');
        if (at === -1) return 'claude';
        const name = argv[at + 1];
        return typeof name === 'string' && Object.prototype.hasOwnProperty.call(RULES_FILE, name) ? name : null;
    }
    
    /** The session of the hook input: Cursor calls it conversation_id, Claude Code and Kiro session_id. */
    function sessionOf(agent, input) {
        const id = agent === 'cursor' ? input.conversation_id : input.session_id;
        if (typeof id !== 'string' || !id) return null;
        return agent === 'claude' ? id : `${agent}-${id}`;
    }
    
    /** The text a tool returned, where the PR URL is looked for. */
    function resultOf(agent, input) {
        if (agent === 'cursor') return textOf(input.output ?? input.result_json);
        if (agent === 'kiro') return textOf(input);
        return textOf(input.tool_response);
    }
    
    /** The shell command that just ran. */
    function commandOf(agent, input) {
        const command = agent === 'cursor' ? input.command : input.tool_input?.command;
        return typeof command === 'string' ? command.slice(0, MAX_SCAN) : '';
    }
    
    function stateFile(sessionId) {
        const id = typeof sessionId === 'string' ? sessionId.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 120) : '';
        if (!id) return null;
        return path.join(process.env.TMPDIR || '/tmp', 'skuld-pr-hooks', `${id}.json`);
    }
    
    function emptyState() {
        return { prs: {}, last: null, pending: null, asked: false };
    }
    
    /** A missing file is an empty state. An unreadable or malformed one throws, and the hook fails open. */
    function loadState(file) {
        if (!file || !fs.existsSync(file)) return emptyState();
        const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
        if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('bad state');
        const prs = raw.prs && typeof raw.prs === 'object' && !Array.isArray(raw.prs) ? raw.prs : {};
        return { prs, last: raw.last ?? null, pending: raw.pending ?? null, asked: raw.asked === true };
    }
    
    function saveState(file, state) {
        if (!file) return;
        fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
        const tmp = `${file}.${process.pid}.tmp`;
        fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 });
        fs.renameSync(tmp, file);
    }
    
    function clip(text) {
        return text.length > MAX_OUTPUT - 200 ? `${text.slice(0, MAX_OUTPUT - 201)}…` : text;
    }
    
    /** A reminder for the agent (`context`) or a refusal to stop (`block`); `answer` writes it the agent's way. */
    const context = (text) => ({ kind: 'context', text: clip(text) });
    const block = (text) => ({ kind: 'block', text: clip(text) });
    
    /** What goes on stdout for this agent, or null for nothing. */
    function answer(agent, out) {
        if (!out) return null;
        if (agent === 'cursor') return out.kind === 'block' ? JSON.stringify({ followup_message: out.text }) : null;
        if (out.kind === 'block') return JSON.stringify({ decision: 'block', reason: out.text });
        if (agent === 'kiro') return out.text;
        return JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: out.text } });
    }
    
    /** `pending` is a PR number, or `true` for a pull request whose number was not found in the tool output. */
    function nameOf(pending) {
        return typeof pending === 'number' ? `PR #${pending}` : 'the pull request you opened';
    }
    
    function stepsFor(ctx, pending, url) {
        const pr = typeof pending === 'number' ? `${pending}` : '<the PR number>';
        return [
            `A pull request was opened${typeof pending === 'number' ? `: PR #${pending}${url ? ` (${url})` : ''}` : ' (its number was not found in the tool output)'}.`,
            `This repository's rules (${ctx.rules}) ask for these steps now:`,
            `1. Skuld MCP get_change with pr ${pr}: the changed flow ids and action keys.`,
            `2. check_scope with pr ${pr}: its line is the Scope line of the summary. On Wide or Sprawling tell the owner and offer the split; it never blocks.`,
            '3. explain_change with headSha = the head commit of the PR (git rev-parse HEAD).',
            `4. render_change_image with pr ${pr}. Put the markdown it returns (scope line, Skuld link, guide, explanation) in the PR body.`,
            `5. Post the summary in chat with the template in ${ctx.where} (image, scope, what changed, why, tests, findings).`,
            '6. Ask the owner: Ready to merge? Then stop.',
            'Never merge, approve or turn on auto-merge without an explicit "merge" from the owner in this conversation.',
            'If the Skuld MCP is not connected, say so in the summary and still ask.',
        ].join('\n');
    }
    
    function afterPr(ctx) {
        const found = PR_URL.exec(resultOf(ctx.agent, ctx.input));
        const state = loadState(ctx.file);
        state.asked = false;
        if (!found) {
            state.pending = true;
            saveState(ctx.file, state);
            return context(stepsFor(ctx, true));
        }
        const n = Number(found[1]);
        state.prs[n] = found[0];
        state.last = n;
        state.pending = n;
        saveState(ctx.file, state);
        return context(stepsFor(ctx, n, found[0]));
    }
    
    function afterPush(ctx) {
        const state = loadState(ctx.file);
        const n = typeof state.last === 'number' && state.prs[state.last] ? state.last : null;
        if (n === null) return null;
        state.pending = n;
        state.asked = false;
        saveState(ctx.file, state);
        return context(
            `You pushed to PR #${n}. The repository's rules (${ctx.rules}) ask for: check_scope and explain_change again for the new head, `
            + 'render_change_image again, update the PR body and the summary in chat, then ask the owner for merge and stop. '
            + 'Never merge without an explicit "merge" from the owner.',
        );
    }
    
    function done(ctx) {
        const state = loadState(ctx.file);
        if (state.pending !== null || state.asked) {
            state.pending = null;
            state.asked = false;
            saveState(ctx.file, state);
        }
        return context(`The change image is ready. Now post the summary in chat (the template in ${ctx.rules}) and ask for merge. Then stop.`);
    }
    
    /** True when the agent is already continuing because of this hook: let it stop, and never block twice in a row. */
    function alreadyAsked(ctx, state) {
        if (ctx.agent === 'claude') return ctx.input.stop_hook_active === true;
        // Cursor counts the follow-ups of a stop hook (loop_count). Kiro's docs name no such field, so the state
        // file remembers that this hook already asked once.
        return state.asked || (ctx.agent === 'cursor' && Number(ctx.input.loop_count) > 0);
    }
    
    function stop(ctx) {
        const state = loadState(ctx.file);
        if (state.pending === null) return null;
        if (alreadyAsked(ctx, state)) {
            state.pending = null;
            state.asked = false;
            saveState(ctx.file, state);
            return null;
        }
        if (ctx.agent !== 'claude') {
            state.asked = true;
            saveState(ctx.file, state);
        }
        const pr = typeof state.pending === 'number' ? ` with pr ${state.pending}` : '';
        return block(
            `The Skuld steps for ${nameOf(state.pending)} are not finished (${ctx.rules}). Before you stop: call get_change${pr}, check_scope, `
            + 'explain_change for the head commit and render_change_image, put the returned markdown in the PR body, post the '
            + `summary in chat with the ${ctx.where} template and ask the owner "Ready to merge?". If the Skuld MCP is not connected, `
            + 'say so in the summary and ask anyway. Never merge without an explicit "merge" from the owner.',
        );
    }
    
    function afterShell(ctx) {
        const command = commandOf(ctx.agent, ctx.input);
        if (PR_CREATE.test(command)) return afterPr(ctx);
        if (GIT_PUSH.test(command)) return afterPush(ctx);
        return null;
    }
    
    function afterMcp(ctx) {
        const tool = typeof ctx.input.tool_name === 'string' ? ctx.input.tool_name : '';
        if (/create_pull_request$/.test(tool)) return afterPr(ctx);
        if (/render_change_image$/.test(tool)) return done(ctx);
        return null;
    }
    
    const MODES = { 'after-pr': afterPr, 'after-push': afterPush, done, stop, 'after-shell': afterShell, 'after-mcp': afterMcp };
    
    async function main() {
        if ((process.env.SKULD_PR_HOOKS || '').trim().toLowerCase() === 'off') return;
        const mode = process.argv[2];
        const agent = agentOf(process.argv.slice(3));
        if (!agent || !Object.prototype.hasOwnProperty.call(MODES, mode)) return;
        const input = JSON.parse(await readStdin());
        if (!input || typeof input !== 'object' || Array.isArray(input)) return;
        const where = RULES_FILE[agent];
        const ctx = { agent, input, file: stateFile(sessionOf(agent, input)), where, rules: `${where}, ${SECTION}` };
        const text = answer(agent, MODES[mode](ctx));
        if (text) process.stdout.write(`${text}\n`);
    }
    
    main().catch(() => {}).finally(() => { process.exitCode = 0; });

    Hooks tested: Claude Code. Cursor and Kiro follow their docs and are not tested yet.

What happens on every pull request

After the agent opens a pull request, and again after every push to it:

  1. get_changeReads Skuld's diff of the pull request: the flows it changed and the knots (actions) on them.
  2. check_scopeMeasures the change: flows and knots touched, how far a shared knot reaches, and a level (Focused, Wide or Sprawling). On a wide one it tells you and offers a split. It never blocks.
  3. explain_changeLeaves its own explanation, tied to the head commit: why the change exists, how it does it, the risks, the tests it ran.
  4. render_change_imageDraws the change as cords and knots. The Skuld link, the step-by-step guide and the explanation go in the pull request body.
  5. Summary in chatPosts the picture, the scope, what changed, why, the test results and the new findings, in one fixed template.
  6. Ready to merge?Asks you, in these words: Ready to merge? Reply "merge" and I'll merge as is. I won't merge without it.
  7. StopWaits for your answer. It never merges, approves or turns on auto-merge without your "merge" in the conversation.

The summary it posts in chat:

the summary template
PR #<n> · <title> · <url>
[the Skuld change image]
Scope: <F> flows (<names>), <K> steps, <R> removed, reach <N> · <Focused|Wide|Sprawling>
What changed: <the guide steps>
Why: <the explanation>
Tests: server p/f/s · web p/f/s · monitor p/f/s (passed/failed/skipped)
Findings: <new errors, or none>
Ready to merge? Reply "merge" and I'll merge as is. I won't merge without it.

If the Skuld MCP is not connected, the agent says so in the summary and still asks. To run the loop by hand, use the MCP prompt finish-pr with the pull request number. The same rules are the MCP resource flows://agents/rules.

Small pull requests: few flows each

Other agents

Rules file and MCP only for now: no hook yet for these agents.

Codex

~/.codex/config.toml
[mcp_servers.skuld]
url = "https://skuldai.com/mcp"
bearer_token_env_var = "SKULD_TOKEN"

Rules: AGENTS.md at the repository root.

GitHub Copilot cloud agent

repository settings, Copilot, MCP configuration
{
  "mcpServers": {
    "skuld": {
      "type": "http",
      "url": "https://skuldai.com/mcp",
      "tools": [
        "get_change",
        "check_scope",
        "explain_change",
        "render_change_image"
      ],
      "headers": {
        "Authorization": "$COPILOT_MCP_SKULD_AUTH"
      }
    }
  }
}

Rules: AGENTS.md. The secret COPILOT_MCP_SKULD_AUTH holds the whole header value, Bearer <token>. Copilot uses MCP tools only, so the prompts and resources are not available there.

Gemini CLI

run once in a terminal
gemini mcp add --transport http --header "Authorization: Bearer $SKULD_TOKEN" skuld https://skuldai.com/mcp

Rules: GEMINI.md, or set context.fileName to AGENTS.md in .gemini/settings.json.

Not a security boundary

Rules and hooks are reminders, not a lock. An agent can ignore a reminder, and a hook matches command text as well as it can. What keeps your main branch safe is that a person merges, so keep the merge in your own hands.

Try it

Create a token, connect your agent, and ask it for a small change. The pull request it opens will carry the picture and end with the question.

Agent tokens needs a sign-in with GitHub.