Agents and MCP

Agents in pipelines

What an agent must handle when Tracehold changes its tools or holds a call for a person, for interactive agents, CI jobs, code-driven steps and agent frameworks, with tested code.

Two things happen to an agent behind Tracehold that a plain API never does:

  1. Its tools change while it is connected: someone adds or removes one on its server.
  2. A call waits for a person: the server's guardrails or an exception say Ask a person, so the call returns "requires human approval" with an Action ID instead of a result.

Who has to do what depends on how the agent runs. The three Python files on this page (wait_for_approval.py, webhook_receiver.py, tool_changes.py) run against a real Tracehold in its backend journey (backend/tests/e2e, part of the full check suite, scripts/test.sh).

At a glance#

How the agent runsTool changesA call held for a person
Interactive (Claude Code, Cursor, VS Code)The client refetches its tools by itselfThe model waits with tracehold_wait_for_approval by itself
Claude Code in a CI job (claude -p)SameSame; give the job enough time (below)
Your own code, step by step (MCP SDK)Refetch on the notice (below)call_with_approval waits in code, no model tokens spent
An agent framework (OpenAI Agents SDK, LangGraph, CrewAI)Lists tools on each runThe model waits, or the run ends and resumes on a webhook

Removing a tool takes effect at once whatever an agent holds: Tracehold refuses calls to tools its server no longer has.

How waiting works#

Every server lists Tracehold's own tool tracehold_wait_for_approval beside yours. A held call's reply names it:

Action requires human approval: Guardrail: Destructive actions are sent to a person on this server
Action ID: 5ecad137-e362-46d2-ab80-3a12bd1b8f22
Approval expires at: 2026-10-24 15:42:07+00:00
To wait for the decision, call tracehold_wait_for_approval with this Action ID: ...

Each call to it waits up to 25 seconds on Tracehold's side:

The persontracehold_wait_for_approval answers
Approves (in Tracehold or Slack)"Approved by who; it ran once." and the call's result: it runs exactly the approved call
Rejects"Rejected by who", and nothing runs
Has not decided"Still waiting for a person (0 of 1 approval so far)": call it again
Lets it expireSays so; make the call again to ask again

A request expires after 30 minutes unless an exception or Settings → Organization says otherwise.

Interactive agents#

Nothing to set up. Asked only to "delete the SNS topic named nightly-report", Claude Code 2.1.296 called the delete, read that it was held, called tracehold_wait_for_approval with the Action ID, got the result when a person approved 10 seconds later, and reported it.

Claude Code in a CI job#

A CI job has no person at a browser, so use a server that takes a token, and name it tracehold in the config so the --allowedTools pattern matches:

{"mcpServers": {"tracehold": {"type": "http", "url": "https://api.tracehold.ai/mcp/<server-id>/",
  "headers": {"Authorization": "Bearer ${TRACEHOLD_TOKEN}"}}}}
claude -p "Rotate the logs bucket's lifecycle rule to 30 days." \
  --mcp-config .tracehold-mcp.json --strict-mcp-config \
  --allowedTools "mcp__tracehold__*" \
  --append-system-prompt "If Tracehold holds a call for approval, keep calling tracehold_wait_for_approval with its Action ID until it is decided."
  • --allowedTools "mcp__tracehold__*" lets it use the server's tools without a prompt; Tracehold decides what runs.
  • The instruction keeps it waiting through a long approval instead of stopping to report that a call is pending.
  • Give the job more time than your approvals take. A model that waits spends a turn every 25 seconds; for approvals that can take an hour, end the run and resume it on a webhook instead (below).

A step in your own code#

A pipeline step that calls a tool directly, with no model deciding, waits in code. call_with_approval calls the tool and, if Tracehold holds it, waits for the decision and returns the approved call's result:

"""Run a Tracehold tool call from code, and wait for a person if Tracehold
holds it. Works with the official MCP Python SDK (ClientSession or Client).
Run by Tracehold's backend journey (backend/tests/e2e)."""
import re

WAIT_TOOL = "tracehold_wait_for_approval"
ACTION_ID = re.compile(r"Action ID: ([0-9a-f-]{36})")


class NotRun(Exception):
    """A person rejected the call, nobody decided before it expired, or it
    was approved but could not run (for example, no connector online)."""


def _text(result) -> str:
    return "\n".join(getattr(part, "text", "") for part in result.content)


def _failed(result) -> bool:
    return bool(getattr(result, "is_error", getattr(result, "isError", False)))


async def call_with_approval(session, name: str, arguments: dict):
    """Call a tool. If Tracehold holds it for a person, wait for the decision
    (each wait lasts up to 25 seconds; this repeats it) and return the result
    of the approved call. Raises NotRun if it does not run."""
    result = await session.call_tool(name, arguments)
    held = ACTION_ID.search(_text(result))
    if not (_failed(result) and held and "requires human approval" in _text(result)):
        return result
    while True:
        result = await session.call_tool(WAIT_TOOL, {"action_id": held.group(1)})
        if _failed(result) and _text(result).startswith("Still waiting"):
            continue
        if _failed(result):
            raise NotRun(_text(result))
        return result
async with ClientSession(read, write) as session:
    await session.initialize()
    try:
        result = await call_with_approval(session, "aws_s3_delete_object",
                                          {"Bucket": "reports", "Key": "2025/old.csv"})
    except NotRun as why:
        # Catch it here, inside the session: an error that leaves the
        # session's `async with` arrives wrapped in an ExceptionGroup.
        fail_the_step(str(why))

Long waits: end the run, resume on a webhook#

An orchestrator (LangGraph, the OpenAI Agents SDK, Temporal, your own queue) does not need to keep anything running while a person decides. Let the run stop at the held call, remember its Action ID, and resume when Tracehold posts the decision:

  1. Set a webhook URL under Settings → Organization (Team and Enterprise) and click Create signing secret; keep the secret where your receiver can read it. The URL must be https on a public address (why). Only owners and admins see the saved address, since it may carry your receiver's token; members see that one is set. Empty the field and save to remove it.
  2. When a person approves or rejects, Tracehold posts action.approved or action.rejected with the action_id, signed with X-Tracehold-Signature.
  3. Your receiver checks the signature, finds the run waiting on that action_id, and resumes it. The resumed step calls tracehold_wait_for_approval once: the call runs and its result comes back.
"""Resume a paused pipeline run when a person decides on a held call:
check that the webhook came from Tracehold, then read which call it is
about. Run by Tracehold's backend journey (backend/tests/e2e)."""
import hashlib
import hmac
import json


def verify(body: bytes, signature: str | None, secret: str) -> dict:
    """The event, if Tracehold signed this exact body with your secret
    (header X-Tracehold-Signature); raises ValueError otherwise."""
    expected = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    if not signature or not hmac.compare_digest(signature, expected):
        raise ValueError("not signed by Tracehold")
    return json.loads(body)


# In your web framework, for example FastAPI:
#
# @app.post("/tracehold-events")
# async def tracehold_event(request: Request):
#     event = verify(await request.body(), request.headers.get("X-Tracehold-Signature"), SECRET)
#     if event["event_type"] in ("action.approved", "action.rejected"):
#         resume_run_waiting_on(event["action_id"], approved=event["event_type"] == "action.approved")
#     return {"ok": True}

An approved call must run within 15 minutes of the approval; after that, make the call again to ask again.

Agent frameworks#

The model sees tracehold_wait_for_approval like any other tool and the held reply tells it what to do, so frameworks need nothing special. Two settings matter:

  • Instructions: add "If Tracehold holds a call for approval, keep calling tracehold_wait_for_approval with its Action ID until it is decided" to the agent's instructions, or end the run and resume on the webhook for long waits.
  • Tool lists: frameworks fetch the server's tools when a run starts; one that caches them across runs (the OpenAI Agents SDK's cache_tools_list) should drop the cache when tools change.

See OpenAI Agents SDK, LangChain and LangGraph and CrewAI for the wiring.

What is tested#

HowVersions
A real model choosing to waitClaude Code, asked only to delete a topic: held, waited, told "still waiting", waited again, approved, doneClaude Code 2.1.296
The code on this pageRun against a real TraceholdMCP Python SDK 2.2 in the backend journey; 1.28 (what frameworks install) in the framework check, scripts/check-agent-frameworks.sh
OpenAI Agents SDKThe wiring on its page, and a run whose model is a scripted stand-in: a held delete reaches the model, it waits until approvedopenai-agents 0.20.0
LangChainThe same with create_agent and langchain-mcp-adapterslangchain 1.4.4, langchain-mcp-adapters 0.3.2
CrewAIThe wiring on its page, and its tools: held, still waiting, approvedcrewai-tools 1.15.27

A stand-in model checks each framework's plumbing (does a held call reach the model, does the run go on) without an API key; Claude Code checks the model's own choice.

Keeping tools current#

Tracehold tells every connected client when its server's tools change (notifications/tools/list_changed, see MCP protocol). Claude Code refetches by itself. With the official MCP Python SDK, mark the list stale when the notice arrives and fetch it before the agent's next step (fetching inside the handler itself deadlocks on SDK 1.x):

"""Keep an agent's tool list current when someone adds or removes a tool on
its Tracehold server, with the official MCP Python SDK (1.x or 2.x).
Tracehold tells connected clients; the list is fetched again before the
agent next uses it. Run by Tracehold's backend journey (backend/tests/e2e)."""
from mcp.types import ToolListChangedNotification


class CurrentTools:
    """Pass `on_message` to ClientSession as its message_handler, and call
    `current(session)` before each step of the agent. The handler only marks
    the list stale: it must not wait for a reply itself, since the SDK
    delivers replies through the same loop that runs it."""

    def __init__(self) -> None:
        self._tools = None
        self._stale = True

    async def on_message(self, message) -> None:
        if isinstance(getattr(message, "root", message), ToolListChangedNotification):
            self._stale = True

    async def current(self, session) -> list:
        if self._stale:
            self._stale = False
            self._tools = (await session.list_tools()).tools
        return self._tools


# tools = CurrentTools()
# async with ClientSession(read, write, message_handler=tools.on_message) as session:
#     await session.initialize()
#     while working:
#         step = await model.next_step(await tools.current(session))