Skip to content

The served server

octomate.mcp.server

Compose gateway, history, todos and installed integrations on one MCP server.

HISTORY_NAMESPACE module-attribute

HISTORY_NAMESPACE = 'history'

TENTACLES_SERVER_NAME module-attribute

TENTACLES_SERVER_NAME = 'tentacles'

LIST_MCP_TOOLS module-attribute

LIST_MCP_TOOLS = 'mcp_list_tools'

LIST_MCPS module-attribute

LIST_MCPS = 'mcp_list_servers'

LIST_MCP_TENTACLES module-attribute

LIST_MCP_TENTACLES = 'mcp_list_tentacles'

INSTALL_MCP module-attribute

INSTALL_MCP = 'mcp_install'

UNINSTALL_MCP module-attribute

UNINSTALL_MCP = 'mcp_uninstall'

ENABLE_MCP module-attribute

ENABLE_MCP = 'mcp_enable'

DISABLE_MCP module-attribute

DISABLE_MCP = 'mcp_disable'

history_tool

history_tool(name: str) -> str

A history tool's served name, from the capability's own.

Source code in octomate/mcp/server.py
def history_tool(name: str) -> str:
    """A history tool's served name, from the capability's own."""
    return f"{HISTORY_NAMESPACE}_{HISTORY_TOOL_NAMES[name]}"

notify_tools_changed async

notify_tools_changed() -> None

Notify the calling client when its protocol supports request-stream updates.

Newer protocol versions require subscriptions, which FastMCP does not serve. The stateless endpoint always exposes current availability through tools/list.

Source code in octomate/mcp/server.py
async def notify_tools_changed() -> None:
    """Notify the calling client when its protocol supports request-stream updates.

    Newer protocol versions require subscriptions, which FastMCP does not serve.
    The stateless endpoint always exposes current availability through tools/list.
    """
    context = get_context()
    request = context.request_context
    if request is not None and request.protocol_version in HANDSHAKE_PROTOCOL_VERSIONS:
        await context.send_notification(ToolListChangedNotification())

tentacle_instructions

tentacle_instructions() -> str
Source code in octomate/mcp/server.py
def tentacle_instructions() -> str:
    return (
        "When searching for tools, also check the MCP servers proxied by Octomate "
        "before concluding that a needed tool is unavailable. "
        f"Call `{LIST_MCPS}` to discover the current user's installed MCPs. "
        f"Use `{SEARCH_MCP_TOOLS}` to find matching tool definitions, or use the "
        "MCP tools/list catalog. Call each discovered tool directly by its exact "
        "name. Search does not change the catalog. "
        f"Use `{LIST_MCP_TOOLS}` to read an installation's upstream instructions "
        "and original tool definitions. "
        f"When the user asks to install an MCP, use `{LIST_MCP_TENTACLES}` to find "
        f"configured offerings, then `{INSTALL_MCP}`. Remote MCPs can also be "
        "installed by HTTPS URL with no authentication or dynamic OAuth. "
        f"Use `{ENABLE_MCP}`, `{DISABLE_MCP}`, and `{UNINSTALL_MCP}` with an "
        "installation's id when the user requests those changes. "
        "If authorization is required, use `oauth_connect` with that namespace "
        "and an available OAuth flow to send the user a private authorization "
        "link, then `oauth_confirm`. Installing does not authorize an MCP. "
        "OAuth links require a channel with private delivery. Enter personal "
        "bearer tokens through the authenticated MCP HTTP API, never tool arguments. "
        "When an unregistered channel user asks to link the profile driving the "
        "current turn to an Octomate account, use `oauth_link_profile`; it privately "
        "delivers the browser flow without accepting or returning an identity."
    )

octomate_instructions

octomate_instructions() -> str
Source code in octomate/mcp/server.py
def octomate_instructions() -> str:
    return "\n".join(
        [
            todo_instructions(),
            gateway_instructions(gateway_tool),
            history_instructions(history_tool),
            tentacle_instructions(),
        ]
    )

tentacles_mcp

tentacles_mcp(
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
    *,
    manager: McpManager,
) -> FastMCP

Serve discovery, calls, and authorization for the current user's MCPs.

Source code in octomate/mcp/server.py
def tentacles_mcp(
    resolve_session: Callable[[], Awaitable[OctomateSession]],
    *,
    manager: McpManager,
) -> FastMCP:
    """Serve discovery, calls, and authorization for the current user's MCPs."""
    mcp = FastMCP(
        name=TENTACLES_SERVER_NAME,
        instructions=tentacle_instructions(),
    )
    mcp.add_provider(InstalledMcpProvider(manager, resolve_session))
    mcp.add_transform(ToolSearch())

    async def resolve_owner(
        # Depends declares injection; FastMCP resolves it separately for each call.
        scope: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> User:
        return await scope.owner()

    oauth = FastMCP(OAUTH_NAMESPACE)
    mount_oauth(oauth, resolve_session, manager=manager, resolve_owner=resolve_owner)
    mcp.mount(oauth, namespace=OAUTH_NAMESPACE)

    @mcp.tool(
        name=LIST_MCP_TENTACLES,
        description="List configured MCP tentacles the current user can install.",
        annotations={"readOnlyHint": True},
    )
    async def list_tentacles(
        scope: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> list[McpTentacleInfo]:
        return manager.available()

    @mcp.tool(
        name=LIST_MCPS,
        description=(
            "List the current user's installed MCPs, including disabled ones, "
            "stored OAuth status, and available authorization flows. Does not poll providers."
        ),
        annotations={"readOnlyHint": True},
    )
    async def list_servers(
        owner: User = Depends(resolve_owner),  # noqa: B008
    ) -> list[McpServerSummary]:
        return [
            await manager.summary(owner, instance)
            for instance in await manager.list(user_id=owner.id)
        ]

    @mcp.tool(
        name=INSTALL_MCP,
        description=(
            "Install an MCP for the current user. For a configured tentacle, pass its "
            "id and URL from mcp_list_tentacles and omit auth. For a remote URL, "
            "choose none or oauth. Namespace is a unique local name without personal/. "
            "Installation enables the MCP; OAuth authorization is a separate step."
        ),
        annotations={"destructiveHint": False},
    )
    async def install(
        name: str,
        namespace: str,
        url: HttpsUrl,
        *,
        tentacle_id: str | None = None,
        auth: Literal["none", "oauth"] | None = None,
        user: User = Depends(resolve_owner),  # noqa: B008
    ) -> McpServerSummary:
        match auth:
            case "none":
                authentication = NoAuth()
            case "oauth":
                authentication = OAuth()
            case None:
                authentication = None
        try:
            instance = await manager.install(
                user_id=user.id,
                request=McpInstallRequest(
                    name=name,
                    namespace=namespace,
                    url=url,
                    tentacle_id=tentacle_id,
                    auth=authentication,
                ),
            )
        except (McpUnavailable, ValueError) as error:
            raise ToolError(str(error)) from error
        await notify_tools_changed()
        return await manager.summary(user, instance)

    @mcp.tool(
        name=ENABLE_MCP,
        description="Enable one of the current user's installed MCPs, keeping its saved authorization.",
        annotations={"destructiveHint": False, "idempotentHint": True},
    )
    async def enable(
        # OpenAI strict mode needs the standard format; UUID7 still validates values.
        mcp_id: Annotated[UUID7, WithJsonSchema({"type": "string", "format": "uuid"})],
        user: User = Depends(resolve_owner),  # noqa: B008
    ) -> McpServerSummary:
        try:
            instance = await manager.enable(user_id=user.id, mcp_id=mcp_id)
        except McpUnavailable as error:
            raise ToolError(str(error)) from error
        await notify_tools_changed()
        return await manager.summary(user, instance)

    @mcp.tool(
        name=DISABLE_MCP,
        description=(
            "Disable one of the current user's MCPs and close its cached client "
            "immediately. Keeps the installation and saved authorization."
        ),
        annotations={"destructiveHint": False, "idempotentHint": True},
    )
    async def disable(
        mcp_id: Annotated[UUID7, WithJsonSchema({"type": "string", "format": "uuid"})],
        user: User = Depends(resolve_owner),  # noqa: B008
    ) -> McpServerSummary:
        try:
            instance = await manager.disable(user_id=user.id, mcp_id=mcp_id)
        except McpUnavailable as error:
            raise ToolError(str(error)) from error
        await notify_tools_changed()
        return await manager.summary(user, instance)

    @mcp.tool(
        name=UNINSTALL_MCP,
        description=(
            "Remove one of the current user's MCP installations and its saved "
            "credentials, closing its cached client immediately. Does not revoke "
            "authorization at the provider."
        ),
        annotations={"destructiveHint": True},
    )
    async def uninstall(
        mcp_id: Annotated[UUID7, WithJsonSchema({"type": "string", "format": "uuid"})],
        scope: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        try:
            await manager.uninstall(user_id=scope.owner_id, mcp_id=mcp_id)
        except McpUnavailable as error:
            raise ToolError(str(error)) from error
        await notify_tools_changed()
        return "MCP uninstalled."

    @mcp.tool(
        name=LIST_MCP_TOOLS,
        description="Load tool schemas for one of the current user's installed MCPs.",
        annotations={"readOnlyHint": True},
    )
    async def list_tools(
        namespace: str,
        user: User = Depends(resolve_owner),  # noqa: B008
    ) -> McpToolCatalog:
        try:
            return await manager.catalog(user, namespace, refresh=True)
        except McpUnavailable as error:
            raise ToolError(str(error)) from error
        except (httpx2.HTTPError, MCPError, TimeoutError) as error:
            raise ToolError("MCP upstream request failed") from error

    return mcp

octomate_mcp

octomate_mcp(
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
    thread_manager: ThreadManager,
    nerves: Nerves,
    *,
    bearers: KnownBearers | None = None,
    manager: McpManager,
    conversations: ConversationManager,
    skills: SkillManager,
) -> FastMCP

Compose the gateway, history, and user-scoped MCP tools over one session resolver.

Source code in octomate/mcp/server.py
def octomate_mcp(
    resolve_session: Callable[[], Awaitable[OctomateSession]],
    thread_manager: ThreadManager,
    nerves: Nerves,
    *,
    bearers: KnownBearers | None = None,
    manager: McpManager,
    conversations: ConversationManager,
    skills: SkillManager,
) -> FastMCP:
    """Compose the gateway, history, and user-scoped MCP tools over one session resolver."""
    auth: AuthProvider | None = bearers
    if bearers is not None and bearers.auth is not None:
        issuer = bearers.auth.config.oauth_issuer_url
        if issuer is not None:
            auth = RemoteAuthProvider(
                token_verifier=bearers,
                authorization_servers=[issuer],
                base_url=issuer,
                resource_base_url=f"{str(issuer).rstrip('/')}/{OCTOMATE_SERVER_NAME}",
                scopes_supported=["mcp"],
            )
    mcp = FastMCP(
        name=OCTOMATE_SERVER_NAME,
        instructions=octomate_instructions(),
        auth=auth,
    )
    gateway = FastMCP(GATEWAY_NAMESPACE)
    mount_gateway(
        gateway, resolve_session, thread_manager, nerves, conversations=conversations
    )
    mcp.mount(gateway, namespace=GATEWAY_NAMESPACE)
    history = FastMCP(HISTORY_NAMESPACE)
    mount_history(history, resolve_session, thread_manager)
    mcp.mount(history, namespace=HISTORY_NAMESPACE)
    todos = FastMCP("todos")
    mount_todos(todos, resolve_session)
    mcp.mount(todos)
    # Installed tools and management helpers already carry their served names.
    mcp.mount(tentacles_mcp(resolve_session, manager=manager))
    mcp.mount(skills_mcp(resolve_session, manager=skills))
    return mcp

octomate.mcp.gateway

The gateway as MCP: the routing spells, served to agent runtimes.

One family on the server octomate.mcp.server composes. Its tools are typed functions whose contracts and schemas are shared by all runtimes, so no two runtimes read two different tools; all that differs is the session a call runs against, which each tool resolves through its declared FastMCP dependency. The mounting side supplies a fixed session resolver for an in-process turn, or a per-request lookup for a server that answers over HTTP.

Refusals are spoken as the model reads them: the GatewayRefusal policy raises becomes a ToolError carrying the same sentence, as it becomes a ModelRetry for Inkling, so every runtime corrects from one wording.

TELEPORT_RECORDED module-attribute

TELEPORT_RECORDED = "Teleporting — this turn ends here; you continue over there, with your context intact."

NATIVE_TELEPORT_STARTED module-attribute

NATIVE_TELEPORT_STARTED = "Teleporting — this conversation continues at the destination, its history with it, in a session Octomate runs there. This session stays as it is."

CONVERSATION_HEADER module-attribute

CONVERSATION_HEADER = 'X-Octomate-Conversation'

CLIENT_HEADER module-attribute

CLIENT_HEADER = 'X-Octomate-Client'

GATEWAY_INSTRUCTION_TEMPLATE module-attribute

GATEWAY_INSTRUCTION_TEMPLATE = "## Gateway — decide where this conversation goes and who handles it\n\nThese tools route the conversation. Default to handling it yourself: if you can answer\nwell or do the work, do it and call none of them. Routing is the exception — reach for a\ntool only when one of the signals below clearly fires.\n\n### Addresses and discovery\nFor `{teleport}`, `destination=null` uses the current address.\nFor `{summon}`, null hands over here; a supplied address starts independent work.\nA destination is a `ChannelAddress` object carrying\n`channel_tentacle_id`, `chat_type`, `chat_id`, `user_id`, and optional\n`channel_thread_id` and `shared` visibility. Use known identifiers and preserve\nvisibility; `user_id` must match the requesting user's linked identity on that\nchannel. When no current conversation is attached, supply an explicit address.\n\n`{inspect}` with `reveal=\"destinations\"` suggests addresses without creating anything.\nTo look further, add `channel` to browse one connected channel a level at a time:\nan address with `metadata.inside` is a place to open by passing that value as\n`inside`, and one without it can host a new thread unless `metadata.barred` says\nwhy not. A channel that cannot be browsed says so.\nYou can also supply a known address directly; discovery is optional, and each\noperation validates the address independently. Suggestions are not an exhaustive\nlist or a guarantee that every spell can use each address.\nFor `{teleport}`, `new_thread=true` is the default. For creation,\nuse `channel_thread_id=null`; an existing thread cannot contain another thread.\n\n### `{summon}` — hand off to another agent\nWithout a destination, summon transfers the conversation to a specialist who takes\nover this turn *and its follow-ups*: a real, sticky handoff. With a destination,\nthe specialist starts independent work in a new thread. Summon only when:\n- The request needs a capability you lack — e.g. running or editing code in a real\n  repository or environment, or a domain another agent is described for.\n- It is substantial specialist work another agent would do markedly better, not\n  something you can handle from what you already know.\n\nDo NOT summon when:\n- You can already answer or do it — length or a technical-sounding topic is not a reason.\n- You are only mildly unsure — ask the user a clarifying question instead.\n- No route clearly fits — handle it yourself or ask; never summon on a guess.\n\nWhen one fires, call `{inspect}` with `reveal=\"routes\"` first to see the agents and what\neach is for. Each route includes model metadata: its description and accepted effort levels.\nUse that metadata to choose a model suited to the work. Set\n`effort` only when the user explicitly asked for a level; otherwise leave it unset so\nthe agent's own default applies. Then `{summon}` — copying its `agent_id` and `model`\nexactly from that route, and writing a self-contained brief since the other agent may\nnot see this chat. Omit `destination` to hand over here; this is refused on a\ngroup's main conversation and in native sessions. Supply a parent address to start\nindependent work there while continuing here, inspecting that channel's routes first.\nThe call returns the new thread's address without waiting for its result. A `project`\nand optional `ref` select its workspace. Native sessions may use this mode without\nuploading history. You yourself are not a valid summon target.\n\nThe `hint` visibly opens the thread; `brief` is the receiver's self-contained task.\nTell the user where to follow the work. Results and follow-ups belong in that thread;\nyour current conversation keeps its owner and history. Unsupported or already nested\ndestinations are refused. Each summon with a destination starts new work;\ndo not repeat a successful call to check its progress.\n\n### `{teleport}` — relocate yourself\nMove this conversation into a new thread that *you* keep handling, carrying\neverything said so far. Use it for multi-step or long-running work that deserves its\nown thread but that you are the right one to do — no other agent involved.\nOmit `destination` or use null for the current address, or supply another address.\nTeleport requires attached conversation history that the agent can copy, and the\ndestination must support continuing that agent. Shared history can only move into\na sub-thread of the current chat; moving to another address requires a private\nsource. If a requested new thread cannot be created, the move fails without\nsilently continuing at its parent.\n\nTo work on a project, add `project` (from `{inspect}` with `reveal=\"projects\"`), and\n`ref` — a branch, tag or commit — only when the default branch is the wrong place to\nstart: the thread you land in is bound to it and you resume in its workspace, where\nwork is kept. A thread about no project runs in a throwaway tree, so do this before\nyou start work, not after. From inside a thread, use `destination=null`,\n`new_thread=false` and `project` to bind this one without opening another.\nBinding the current thread always resumes your work in its project workspace.\nStaying put requires a project; a thread binds once, and a different project is\na different thread. Native sessions must move into a new thread.\n\n### `{scheme}` — take it to the user privately\nContinue one-to-one with the person who asked, in their direct messages: for work that\nis theirs alone, or that does not belong in front of the group. Whoever already handles\ntheir direct messages picks it up, so write `brief` self-contained — it may not be you,\nand they cannot see this chat. `hint` opens the conversation over there and is the\nfirst thing they read; nothing is posted here, so close out your own reply by saying\nthe work is moving, not what it is. Its destination is a target object with\n`kind=\"dm\"`, optionally naming a connected `channel` ID for the user's linked\naccount there. Omitting the destination uses this channel's DM; that local move\nrequires a shared source. Another connected channel's DM can also be selected\nfrom a private source. The tool refuses unsupported or unlinked destinations.\n\n### `{dismiss}` — give the workspace back when the work is done\nA thread about a project keeps its workspace between turns, which is what makes its\nnext turn a resume. When the work is finished for good — merged, delivered, or\ndropped — say so with `{dismiss}`: the tree is released when this turn ends, after\nthis turn's work is saved to the project's mirror, and a later message here forks it\nafresh from there, so nothing is lost but the disk. Not for a pause — a thread\nwaiting on someone keeps its tree, and idle ones are swept on their own. Wrap up in\nthe same turn; your working directory goes with it.\n"

HANDOFF_INSTRUCTION module-attribute

HANDOFF_INSTRUCTION = "\n\n### Writing a brief\nA `summon` or `scheme` brief is the receiver's whole opening prompt, and it is\nbudgeted. Say, in this order and only where it changes what they do next: the goal\nin the user's own words; the constraints they set; the decisions made and why; what\nis done; what was tried and failed, so it is not tried again; what is left, first\nitem first; and what a finished result looks like. Leave the rest to the ledger:\nthe receiver reads every thread this person has spoken in, so cite a message by\nits `#msg:<id>` handle and name what to search for instead of repeating it. Do\nnot restate the project — the workspace's own instructions carry that.\n"

SEND_INSTRUCTION_TEMPLATE module-attribute

SEND_INSTRUCTION_TEMPLATE = "\n### `{send}` — deliver something now, without ending your turn\nFor a progress update, an intermediate result, or an image/file you produced along\nthe way. Anything sent this way is already delivered: your final reply continues from\nthere — summarize or extend it, never restate it. If everything worth saying went out\nalready, close with a short wrap-up rather than re-sending it.\n\n`destination` defaults to a target object with `kind=\"here\"`. A target with\n`kind=\"dm\"` delivers to the person who asked, privately —\nfor something that is *for them*, like a summary sent over; say in your reply that you\nsent it. `dm` hands nothing over: you keep this conversation and nobody picks the work\nup there, so use `{scheme}` when the work itself should continue privately. Asking for\n`dm` while already in that person's direct messages is fine — it lands here.\nA DM target can name a connected `channel` ID to reach their linked account there.\nIf no current conversation is attached, that channel must be explicit. Use the\nselected address's `channel_tentacle_id` as `channel`; the recipient is resolved\nfrom the user's linked profile.\n\nTo thread onto a specific message in a busy chat, lead with a reply segment whose id\nis that message's `#msg:<id>` handle — it must be the first segment. To ping someone,\nuse an `at` segment with their user id.\n"

COMMISSION_INSTRUCTION_TEMPLATE module-attribute

COMMISSION_INSTRUCTION_TEMPLATE = "\n### `{commission}` — put another agent to work in the background (you keep the conversation)\nWhere `{summon}` hands the conversation away, `{commission}` does not: another agent works a\nself-contained task and the tool returns its report — the user sees only your reply.\nCall `{inspect}` with `reveal=\"routes\"` and no `channel` to choose a route from this\nconversation's channel; the same model and effort rules as `{summon}` apply.\nGive the accomplice a short mnemonic `name`. The brief must stand alone: the\naccomplice cannot see this chat and has no user to ask, so include the goal, the\nrelevant context, and what a finished result looks like. Several commissions in one\nreply run concurrently.\n\n### `{whisper}` — a quiet word to an accomplice\nContinue an accomplice's work by `name`: it remembers everything it did. Use it to\nrefine or extend that work instead of commissioning a new accomplice.\n"

gateway_instructions

gateway_instructions(
    tool_name: Callable[[GatewayTool], str],
) -> str

The gateway's routing instruction, each spell rendered by the caller's own tool naming — the identity for Inkling, gateway_… on the served server — so every agent reads one contract under the names its runtime lists the tools by.

Source code in octomate/mcp/gateway.py
def gateway_instructions(tool_name: Callable[[GatewayTool], str]) -> str:
    """The gateway's routing instruction, each spell rendered by the caller's own tool
    naming — the identity for Inkling, `gateway_…` on the served server — so every
    agent reads one contract under the names its runtime lists the tools by."""
    names = {
        "inspect": tool_name(GatewayTool.INSPECT),
        "summon": tool_name(GatewayTool.SUMMON),
        "teleport": tool_name(GatewayTool.TELEPORT),
        "scheme": tool_name(GatewayTool.SCHEME),
        "send": tool_name(GatewayTool.SEND),
        "dismiss": tool_name(GatewayTool.DISMISS),
        "commission": tool_name(GatewayTool.COMMISSION),
        "whisper": tool_name(GatewayTool.WHISPER),
    }
    return (
        GATEWAY_INSTRUCTION_TEMPLATE.format(**names)
        + SEND_INSTRUCTION_TEMPLATE.format(**names)
        + COMMISSION_INSTRUCTION_TEMPLATE.format(**names)
    )

spoken

spoken(
    spell: Callable[SpellP, Awaitable[SpellT]],
) -> Callable[SpellP, Awaitable[SpellT]]

A spell with its refusal spoken as the model reads it: a ToolError carrying the gateway's sentence verbatim, as ModelRetry does for Inkling. A refusal is ordinary traffic, not a failure, and is logged as such — anything else that escapes a spell is a real error and keeps FastMCP's own handling.

Source code in octomate/mcp/gateway.py
def spoken[**SpellP, SpellT](
    spell: Callable[SpellP, Awaitable[SpellT]],
) -> Callable[SpellP, Awaitable[SpellT]]:
    """A spell with its refusal spoken as the model reads it: a `ToolError` carrying
    the gateway's sentence verbatim, as `ModelRetry` does for Inkling. A refusal is
    ordinary traffic, not a failure, and is logged as such — anything else that
    escapes a spell is a real error and keeps FastMCP's own handling."""

    @wraps(spell)
    async def cast(*args: SpellP.args, **kwargs: SpellP.kwargs) -> SpellT:
        try:
            return await spell(*args, **kwargs)
        except GatewayRefusal as refusal:
            raise ToolError(str(refusal), log_level=logging.INFO) from refusal

    return cast

served_session

served_session(
    octomate: Octomate,
) -> Callable[[], Awaitable[OctomateSession]]

The session a call served over HTTP runs against.

Every call speaks for the registered user its verified bearer names. A driven turn names its conversation with CONVERSATION_HEADER, written into its launch config by Octomate itself along with the kicker's own secret, and resolves to the session registered while that run is in flight — a bearer other than the kicker's is refused, so no user can drive another's turn. A native session names its agent with CLIENT_HEADER, written once at install time, and gets native_session built for the bearer's user. Identity is asserted by config and credential either way, never chosen by the model, so a call carrying neither header is refused outright rather than guessed at.

Source code in octomate/mcp/gateway.py
def served_session(octomate: Octomate) -> Callable[[], Awaitable[OctomateSession]]:
    """The session a call served over HTTP runs against.

    Every call speaks for the registered user its verified bearer names. A driven
    turn names its conversation with `CONVERSATION_HEADER`, written into its
    launch config by Octomate itself along with the kicker's own secret, and
    resolves to the session registered while that run is in flight — a bearer
    other than the kicker's is refused, so no user can drive another's turn. A
    native session names its agent with `CLIENT_HEADER`, written once at
    install time, and gets `native_session` built for the bearer's user.
    Identity is asserted by config and credential either way, never chosen by
    the model, so a call carrying neither header is refused outright rather than
    guessed at."""

    async def resolve() -> OctomateSession:
        headers = get_http_headers()
        access = get_access_token()
        principal = access.subject if access is not None else None
        named = headers.get(CONVERSATION_HEADER.lower())
        if named is not None:
            try:
                conversation_id = uuid.UUID(named)
            except ValueError:
                raise ToolError(
                    f"{CONVERSATION_HEADER} is not a conversation id: {named!r}."
                ) from None
            session = octomate.gateway.get(conversation_id)
            if session is None:
                raise ToolError(
                    f"No turn of conversation {named} is at the gateway; a session "
                    "reaches it only while the run that opened it is in flight."
                )
            kicker = await octomate.users.get(session.owner_id)
            if kicker is None or kicker.username != principal:
                raise ToolError(
                    f"Conversation {named}'s turn is not this bearer's to drive: "
                    "a driven session speaks with its kicker's own credential, "
                    "which its launch config carries."
                )
            return session
        client = headers.get(CLIENT_HEADER.lower())
        if client is None:
            raise ToolError(
                "This call names no identity: a driven turn names its conversation "
                f"with {CONVERSATION_HEADER}, a native session its agent with "
                f"{CLIENT_HEADER}. Both are written by config, so a call carrying "
                "neither has nothing the gateway may answer for."
            )
        if principal is None:
            raise ToolError(
                "A native session speaks for a registered user, and this call's "
                "bearer names none. Run `octomate configure --token` with "
                "their API token on their machine, then re-run the harness's "
                "`mcp install` command."
            )
        return await native_session(octomate, client, principal)

    return resolve

native_session async

native_session(
    octomate: Octomate,
    agent_tentacle_id: str,
    username: str,
) -> OctomateSession

An ephemeral gateway for one native call, never registered.

username is the verified bearer's owner, so the session speaks for that person: anchored on a transient profile of theirs, its destinations are their own linked accounts. The call is attributed to the configured agent, never to a terminal session, so the session has no thread and no address — every destination is a crossing. A static MCP config puts the tools in every session once installed, and the bearer is the only control.

Source code in octomate/mcp/gateway.py
async def native_session(
    octomate: Octomate, agent_tentacle_id: str, username: str
) -> OctomateSession:
    """An ephemeral gateway for one native call, never registered.

    `username` is the verified bearer's owner, so the session speaks for that
    person: anchored on a transient profile of theirs, its destinations are
    their own linked accounts. The call is attributed to the configured agent, never
    to a terminal session, so the session has no thread and no address — every
    destination is a crossing. A static MCP config puts the tools in every
    session once installed, and the bearer is the only control.
    """
    agent = octomate.agents.get(agent_tentacle_id)
    if agent is None:
        raise ToolError(
            f"{CLIENT_HEADER} names no configured agent: {agent_tentacle_id!r}."
        )
    profile = await octomate.users.native_profile(agent.id, username)
    if profile is None:
        raise RuntimeError(
            f"the bearer verified as {username!r} but the registry holds no such user"
        )
    return OctomateSession(
        channel_routes=octomate.gateway.available_routes(
            octomate.channels, octomate.agents
        ),
        current_agent_id=agent.id,
        channels=octomate.channels,
        users=octomate.users,
        user_profile=profile,
        agents=octomate.agents,
        native=True,
        threads=octomate.threads,
        workspaces=octomate.workspaces,
        nerves=octomate.nerves,
    )

caller_thread

caller_thread() -> str | None

The native session a call came from, where its runtime says so itself: Codex names its thread in every call's _meta.

Source code in octomate/mcp/gateway.py
def caller_thread() -> str | None:
    """The native session a call came from, where its runtime says so itself:
    Codex names its thread in every call's `_meta`."""
    request = get_context().request_context
    meta = request.meta if request is not None else None
    thread_id = (meta or {}).get("threadId")
    return thread_id if isinstance(thread_id, str) and thread_id else None

mount_gateway

mount_gateway(
    mcp: FastMCP,
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
    thread_manager: ThreadManager,
    nerves: Nerves,
    *,
    conversations: ConversationManager,
) -> None

Register the gateway's spells on mcp.

resolve_session supplies each tool's FastMCP dependency: a fixed session for a server mounted in-process for one turn, or a per-request lookup over HTTP. thread_manager is the ledger a delivering spell writes through. nerves is how a native session's teleport or scheme becomes its own turn at once.

Source code in octomate/mcp/gateway.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def mount_gateway(
    mcp: FastMCP,
    resolve_session: Callable[[], Awaitable[OctomateSession]],
    thread_manager: ThreadManager,
    nerves: Nerves,
    *,
    conversations: ConversationManager,
) -> None:
    """Register the gateway's spells on `mcp`.

    `resolve_session` supplies each tool's FastMCP dependency: a fixed session for
    a server mounted in-process for one turn, or a per-request lookup over HTTP.
    `thread_manager` is the ledger a delivering spell writes through. `nerves` is how
    a native session's teleport or scheme becomes its own turn at once.
    """

    @mcp.tool(
        name=GatewayTool.INSPECT,
        annotations={"readOnlyHint": True},
    )
    @spoken
    async def inspect(
        reveal: InspectFacet,
        channel: str | None = None,
        inside: str | None = None,
        cursor: str | None = None,
        limit: Annotated[int | None, Field(ge=1, le=100)] = None,
        # Depends declares injection; FastMCP resolves it separately for each call.
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """Reveal one facet of what this conversation can reach.

        Args:
            reveal: `routes` — agent/model choices on the current or selected channel.
                In-place summon and commission use the current channel's routes;
                summon with a destination uses that channel's routes.
                `destinations` — optional address suggestions, validated independently
                when used; known addresses need not appear in this list. With
                `channel`, one level of that channel's addresses instead.
                `projects` — the projects this deployment can work on, for `teleport`.
            channel: A connected channel ID from an address. For `routes`, omit it
                to inspect the current conversation's routes. For `destinations`,
                name it to browse that channel as the requesting user: an address
                whose `metadata.inside` is set is a place to open, one without it
                can host a new thread unless `metadata.barred` says why not.
            inside: For `destinations` with `channel`, the `metadata.inside` of a
                listed address, to list what that place holds. Omit it for the
                channel's top level.
            cursor: For `projects`, the continuation returned by the previous page.
            limit: For `projects`, page size from 1 to 100; defaults to 20.
        """
        if reveal == "projects":
            page = await session.inspect(
                "projects", channel, inside, cursor=cursor, limit=limit
            )
            content = "\n".join(map(str, page.items)) or "- (none)"
            if page.has_more:
                content += (
                    f"\nNext page: call inspect with reveal='projects', "
                    f"cursor={page.next_cursor!r}."
                )
            return content
        if reveal == "destinations":
            addresses = await session.inspect(
                "destinations", channel, inside, cursor=cursor, limit=limit
            )
            return (
                TypeAdapter(list[ChannelAddress]).dump_json(addresses).decode()
                if addresses
                else "- (none)"
            )
        # Lines, never the list: FastMCP renders an empty list as no content at all.
        return (
            "\n".join(
                str(one)
                for one in await session.inspect(
                    reveal, channel, inside, cursor=cursor, limit=limit
                )
            )
            or "- (none)"
        )

    @mcp.tool(name=GatewayTool.SUMMON)
    @spoken
    async def summon(
        agent_id: str,
        model: str,
        hint: str,
        reason: str,
        brief: Annotated[str, Field(max_length=8_000)],
        effort: str | None = None,
        destination: ChannelAddress | None = None,
        project: str | None = None,
        ref: str | None = None,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str | ChannelAddress:
        """Hand over here, or start another agent in a new independent thread.

        Omit destination to hand over this conversation when the turn ends.
        Supply a parent address to open independent work immediately and return
        its thread address without waiting for a result. The current conversation
        keeps its agent, history and pending decision. Native sessions may use
        a destination without uploading history.

        Args:
            agent_id: The target agent, copied exactly from an `inspect` route
                (`reveal="routes"`).
            model: That route's model, copied exactly.
            hint: A short, user-facing note announcing the handoff, recorded with it.
            reason: One line on why this agent fits — recorded with the handoff, not
                shown to the user as the reply.
            brief: The self-contained brief the other agent starts from. It becomes
                their opening prompt and they cannot see this conversation, so give
                the goal, the relevant context and decisions, what's been tried, and
                what a finished result looks like. If anything you carry says how to
                hand off — a handoff skill, a plugin, your own harness's instructions
                — follow it; this is the floor. Reference rather than repeat: the
                receiver reads every thread this person has spoken in, so cite a
                message by its `#msg:<id>` handle and say what to search for instead
                of pasting it. A brief over the size budget is refused, never trimmed.
            effort: How hard the agent should think, from the effort levels the
                model metadata offers. Set it only when the user explicitly asked
                for a level; omitted, the agent's own default applies.
            destination: A parent address at which to create a new thread. Use
                this channel's inspected routes and the requester's linked identity.
                Omit for an in-place handoff. Existing threads cannot be parents.
            project: An enabled project for the new thread; requires a destination
                and a registered user. Omit for a throwaway workspace.
            ref: A starting branch, tag or commit for that project; requires project.
        """
        return await session.summon(
            agent_id=agent_id,
            model=model,
            hint=hint,
            reason=reason,
            brief=brief,
            effort=effort,
            destination=destination,
            project=project,
            ref=ref,
        )

    @mcp.tool(name=GatewayTool.TELEPORT)
    @spoken
    async def teleport(
        hint: str,
        destination: ChannelAddress | None = None,
        project: str | None = None,
        ref: str | None = None,
        new_thread: bool = True,
        resume: bool = False,
        session_id: Annotated[
            str | None,
            Field(
                description="Filled in by Octomate's own hook for a session you "
                "were not started by Octomate in; leave it out."
            ),
        ] = None,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str | JsonObject:
        """Continue this conversation yourself somewhere else; everything said so
        far comes with you. This turn ends on it, and your context is intact
        there.

        Args:
            hint: The short, user-facing thread-starter message.
            destination: The address at which to create a thread; omit for the
                current chat. The owning channel validates it independently of
                discovery and requires the requesting user's linked identity.
                Shared history stays under its current parent. Teleport requires
                attached history that the agent can copy.
            new_thread: Create a thread before continuing. Set false only to bind
                the current thread to a project without opening another one.
                Binding the current thread always resumes your work.
                For creation, the address must have no `channel_thread_id`.
            project: A project's name, copied exactly from `inspect`
                (`reveal="projects"`), for a conversation about no project: the
                thread you land in is bound to it, and you resume in its workspace,
                where work is kept. A conversation about a project carries it
                wherever it goes, so omit this there.
            ref: The branch, tag or commit that workspace starts from; omit it for
                the project's default branch.
            resume: Carry on working in a new thread at once, as after any tool
                call. Leave it false when the move is all that was asked: you
                continue when the user next writes there. Ignored when
                new_thread is false: binding the current thread always resumes.
        """
        native_session_id = (session_id or caller_thread()) if session.native else None
        if native_session_id is not None:
            await session.attach_native_thread(native_session_id)
        decision = await session.teleport(
            hint=hint,
            destination=destination,
            new_thread=new_thread,
            project=project,
            ref=ref,
            resume=resume,
        )
        request = get_context().request_context
        if (
            not session.native
            and request is not None
            and request.meta is not None
            and request.meta.get("defer_teleport") is True
        ):
            return decision.metadata()
        if not session.native:
            return TELEPORT_RECORDED
        signal = session.native_handoff()
        nerves.signals.dispatch(AgentTopic(signal.agent_id), signal)
        return NATIVE_TELEPORT_STARTED

    @mcp.tool(name=GatewayTool.SCHEME)
    @spoken
    async def scheme(
        hint: str,
        brief: Annotated[str, Field(max_length=8_000)],
        destination: SchemeTarget = DIRECT_TARGET,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """Continue this with the user one-to-one, in their direct messages.

        Whoever already handles that user's direct messages picks the work up — you do
        not choose them, and their direct messages keep the owner they had. Use it for
        work that is that person's alone, or that does not belong in front of the group.

        Args:
            hint: The short, user-facing line that opens the conversation over there,
                where they will read it before anything else. Say that the work is
                being picked up — not the brief, which is written for whoever answers.
            brief: The self-contained brief whoever answers there starts from. They
                cannot see this conversation, so give the goal, the relevant context and
                decisions, what's been tried, and what a finished result looks like. If
                anything you carry says how to hand off — a handoff skill, a plugin,
                your own harness's instructions — follow it; this is the floor.
                Reference rather than repeat: the receiver reads every thread this
                person has spoken in, so cite a message by its `#msg:<id>` handle and
                say what to search for instead of pasting it. A brief over the size
                budget is refused, never trimmed.
            destination: A target object with `kind="dm"`. Omit `channel` for this
                channel's DM when moving from a shared source, or name another
                connected channel ID, including from a private source. The user's
                linked profile determines the recipient.
        """
        sentence = await session.scheme(hint=hint, brief=brief, destination=destination)
        if session.native:
            signal = session.native_handoff()
            nerves.signals.dispatch(AgentTopic(signal.agent_id), signal)
        return sentence

    @mcp.tool(name=GatewayTool.SEND)
    @spoken
    async def send(
        segments: list[MessageSegment],
        destination: SendTarget = HERE_TARGET,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """Deliver these segments immediately, without ending your turn — a progress
        update, an intermediate result, an image or a file. What you send here is
        already delivered: do NOT repeat it in your final reply.

        Args:
            segments: What to deliver.
            destination: A target object with `kind="here"` (the default) or
                `kind="dm"`. A DM target can name a connected `channel` ID; omit
                it for this channel. With no current conversation, name a channel
                explicitly. When choosing from an inspected address, use its
                `channel_tentacle_id` as `channel`; the linked profile supplies the
                recipient. Say in your reply when you sent it elsewhere.
        """
        address = await session.resolve_send(destination)
        target = address if address is not None else session.conversation_address
        if target is None:
            raise GatewayRefusal(
                "This session has no conversation of its own to land a send on — "
                'use a destination with kind="dm" and an explicit connected channel ID.'
            )
        notice = "sent"
        private = False
        if address is not None:
            channel = session.channels[target.channel_tentacle_id]
            dm = await channel.open_dm(target.user_id)
            if dm is not None:
                target = dm
                private = True
            else:
                fallback = session.conversation_address
                if fallback is None:
                    raise GatewayRefusal(
                        f"{channel.name} could not open a direct message with "
                        f"{target.user_id!r}; nothing was delivered."
                    )
                # Mirror React's own fallback: land it where the run lives, and say so.
                target = fallback
                notice = (
                    f"could not open their direct messages on {channel.name}; "
                    "delivered to this conversation instead"
                )
        channel = session.channels[target.channel_tentacle_id]
        message = await thread_manager.record_outbound(
            target,
            agent_tentacle_id=session.current_agent_id,
            segments=segments,
            sender=channel.self_profile,
            owner_id=session.owner_id,
        )
        sent = MessageSentEvent(
            segments=segments, destination=target, thread_message_id=message.id
        )
        await session.publish(target, sent, private=private)
        return notice

    @mcp.tool(name=GatewayTool.DISMISS)
    @spoken
    async def dismiss(
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """Give this thread's workspace back, now that the work in it is done —
        merged, delivered, or dropped for good, not paused. It is released when
        this turn ends, after this turn's work is saved to the project's mirror,
        so nothing is lost: a later message on this thread forks it afresh from
        there. Only the disk goes, and it goes now rather than after the idle
        window the sweep would otherwise wait out.
        """
        return await session.dismiss()

    def parent_call(session: OctomateSession) -> str | None:
        if session.conversation_id is None:
            raise ToolError("Accomplice tools require an active conversation.")
        request = get_context().request_context
        tool_call_id = (
            request.meta.get("tool_call_id")
            if request is not None and request.meta is not None
            else None
        )
        if tool_call_id is not None and (
            not isinstance(tool_call_id, str) or not tool_call_id
        ):
            raise ToolError(
                "The tool call id in request metadata must be a non-empty string."
            )
        return tool_call_id

    @mcp.tool(name=GatewayTool.COMMISSION)
    @spoken
    async def commission(
        name: str,
        agent_id: str,
        model: str,
        brief: str,
        effort: str | None = None,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """Draw another Octomate agent into working a task and get its report
        back — the user sees none of it.

        Args:
            name: Your name for this accomplice — short and mnemonic, e.g.
                `repo-audit`. `whisper` to it later to follow up.
            agent_id: The agent to draw in, copied exactly from an
                `inspect` route for this conversation's channel (omit `channel`).
            model: That route's model, copied exactly.
            brief: The self-contained work order. The accomplice cannot see
                this conversation and has no user to ask, so give the
                goal, the relevant context and decisions, and what a
                finished result looks like.
            effort: How hard the accomplice should think, from the levels the
                model metadata offers. Set it only when the user
                explicitly asked for a level.
        """
        tool_call_id = parent_call(session)
        assert session.conversation_id is not None
        return await session.commission(
            conversations=conversations,
            parent_id=session.conversation_id,
            parent_run_id=None,
            parent_tool_call_id=tool_call_id,
            name=name,
            agent_id=agent_id,
            model=model,
            brief=brief,
            effort=effort,
        )

    @mcp.tool(name=GatewayTool.WHISPER)
    @spoken
    async def whisper(
        name: str,
        message: str,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        """A quiet word to an accomplice you commissioned. It keeps
        everything it did — your whisper continues its work, not a fresh
        start.

        Args:
            name: The name you gave the accomplice when you commissioned it.
            message: The follow-up work order — self-contained, like a
                brief; the accomplice still cannot see this conversation.
        """
        tool_call_id = parent_call(session)
        assert session.conversation_id is not None
        return await session.whisper(
            conversations=conversations,
            parent_id=session.conversation_id,
            parent_run_id=None,
            parent_tool_call_id=tool_call_id,
            name=name,
            message=message,
        )

octomate.mcp.todos

Conversation-scoped todos served through the authenticated Octomate session.

TODO_TOOL_NAMES module-attribute

TODO_TOOL_NAMES = frozenset(
    {
        "read_todos",
        "write_todos",
        "add_todo",
        "update_todo_status",
        "remove_todo",
        "add_subtask",
        "set_dependency",
        "get_available_tasks",
    }
)

TODO_INSTRUCTION module-attribute

TODO_INSTRUCTION = '## Task management\n\nYou have todo tools to plan and track multi-step work:\n- `read_todos` — view the current tasks with their ids and statuses.\n- `write_todos` — replace the whole list (use to lay out or restructure a plan).\n- `add_todo` — append one task without disturbing the rest.\n- `update_todo_status` — move a task between pending / in_progress / completed.\n- `remove_todo` — delete a task by id.\n- `add_subtask` / `set_dependency` / `get_available_tasks` — break tasks down,\n  order them, and find what is unblocked.\n\nUse them for non-trivial work (3+ steps). Keep exactly one task `in_progress`,\nmark tasks `completed` immediately when done, and pass each task an imperative\n`content` ("Run tests") plus a present-continuous `active_form` ("Running tests").\n'

TodoTools dataclass

Conversation-scoped todo tools and the events their mutations produce.

Source code in octomate/mcp/todos.py
@dataclass
class TodoTools:
    """Conversation-scoped todo tools and the events their mutations produce."""

    conversation_id: UUID7
    manager: TodoManager = field(default_factory=TodoManager)

    async def read_todos(self, hierarchical: bool = False) -> str:
        """List the current todos with their ids and statuses."""
        todos = await self.manager.list_todos(self.conversation_id)
        if not todos:
            return "No todos yet. Use write_todos or add_todo to create some."
        return render_todos(todos, hierarchical=hierarchical)

    async def write_todos(self, todos: list[TodoItem]) -> tuple[str, list[TodoEvent]]:
        """Replace the whole todo list with `todos`."""
        items: list[TodoWrite] = [
            TodoWrite(
                content=item.content,
                status=item.status,
                active_form=item.active_form,
                ref=item.id,
                parent_ref=item.parent_id,
                depends_on=item.depends_on,
            )
            for item in todos
        ]
        deleted, created = await self.manager.write_todos(self.conversation_id, items)
        events: list[TodoEvent] = [TodoDeletedEvent(todo=todo) for todo in deleted]
        events += [TodoCreatedEvent(todo=todo) for todo in created]
        return (f"Wrote {len(created)} todos.", events)

    async def add_todo(
        self, content: str, active_form: str
    ) -> tuple[str, list[TodoEvent]]:
        """Append a single new todo (status pending)."""
        todo = await self.manager.add_todo(
            self.conversation_id, content=content, active_form=active_form
        )
        return (f"Added '{content}' (id: {todo.ref}).", [TodoCreatedEvent(todo=todo)])

    async def update_todo_status(
        self, todo_id: str, status: TodoStatus
    ) -> str | tuple[str, list[TodoEvent]]:
        """Change a todo's status by id."""
        conv = self.conversation_id
        previous = await self.manager.get_todo(conv, todo_id)
        if previous is None:
            return f"No todo with id '{todo_id}'."
        if status == "in_progress":
            if is_blocked(previous, by_ref(await self.manager.list_todos(conv))):
                return (
                    f"Cannot start '{previous.content}' — it has incomplete "
                    "dependencies."
                )
        updated = await self.manager.update_todo(conv, todo_id, status=status)
        if updated is None:
            return f"No todo with id '{todo_id}'."
        return (
            f"Updated '{updated.content}' → {status}.",
            update_events(updated, previous),
        )

    async def remove_todo(self, todo_id: str) -> str | tuple[str, list[TodoEvent]]:
        """Delete a todo by id."""
        removed = await self.manager.remove_todo(self.conversation_id, todo_id)
        if removed is None:
            return f"No todo with id '{todo_id}'."
        return (f"Removed '{removed.content}'.", [TodoDeletedEvent(todo=removed)])

    async def add_subtask(
        self, parent_id: str, content: str, active_form: str
    ) -> str | tuple[str, list[TodoEvent]]:
        """Add a subtask under an existing todo."""
        conv = self.conversation_id
        parent = await self.manager.get_todo(conv, parent_id)
        if parent is None:
            return f"No parent todo with id '{parent_id}'."
        todo = await self.manager.add_todo(
            conv, content=content, active_form=active_form, parent_ref=parent_id
        )
        return (
            f"Added subtask '{content}' (id: {todo.ref}, parent: {parent_id}).",
            [TodoCreatedEvent(todo=todo)],
        )

    async def set_dependency(
        self, todo_id: str, depends_on_id: str
    ) -> str | tuple[str, list[TodoEvent]]:
        """Make `todo_id` depend on `depends_on_id` (blocks it until that completes)."""
        conv = self.conversation_id
        todos = await self.manager.list_todos(conv)
        todos_by_ref = by_ref(todos)
        todo = todos_by_ref.get(todo_id)
        dependency = todos_by_ref.get(depends_on_id)
        if todo is None:
            return f"No todo with id '{todo_id}'."
        if dependency is None:
            return f"No todo with id '{depends_on_id}'."
        if todo_id == depends_on_id:
            return "A todo cannot depend on itself."
        if has_cycle(todos, todo_id, depends_on_id):
            return "Cannot add dependency: it would create a cycle."
        if depends_on_id in todo.depends_on:
            return "That dependency already exists."
        new_status: TodoStatus = todo.status
        if dependency.status != "completed" and todo.status not in (
            "completed",
            "blocked",
        ):
            new_status = "blocked"
        updated = await self.manager.update_todo(
            conv,
            todo_id,
            depends_on=[*todo.depends_on, depends_on_id],
            status=new_status,
        )
        if updated is None:
            return f"No todo with id '{todo_id}'."
        message = f"'{todo.content}' now depends on '{dependency.content}'."
        if new_status == "blocked" and todo.status != "blocked":
            message += " Task blocked until the dependency completes."
        return (message, update_events(updated, todo))

    async def get_available_tasks(self) -> str:
        """List tasks with no incomplete dependencies (workable now)."""
        available = available_tasks(await self.manager.list_todos(self.conversation_id))
        if not available:
            return "No available tasks — all are completed or blocked."
        lines = ["Available tasks:"]
        for index, todo in enumerate(available, 1):
            marker = STATUS_MARKERS.get(todo.status, "[ ]")
            lines.append(f"{index}. {marker} [{todo.ref}] {todo.content}")
        return "\n".join(lines)

conversation_id instance-attribute

conversation_id: UUID7

manager class-attribute instance-attribute

manager: TodoManager = field(default_factory=TodoManager)

read_todos async

read_todos(hierarchical: bool = False) -> str

List the current todos with their ids and statuses.

Source code in octomate/mcp/todos.py
async def read_todos(self, hierarchical: bool = False) -> str:
    """List the current todos with their ids and statuses."""
    todos = await self.manager.list_todos(self.conversation_id)
    if not todos:
        return "No todos yet. Use write_todos or add_todo to create some."
    return render_todos(todos, hierarchical=hierarchical)

write_todos async

write_todos(
    todos: list[TodoItem],
) -> tuple[str, list[TodoEvent]]

Replace the whole todo list with todos.

Source code in octomate/mcp/todos.py
async def write_todos(self, todos: list[TodoItem]) -> tuple[str, list[TodoEvent]]:
    """Replace the whole todo list with `todos`."""
    items: list[TodoWrite] = [
        TodoWrite(
            content=item.content,
            status=item.status,
            active_form=item.active_form,
            ref=item.id,
            parent_ref=item.parent_id,
            depends_on=item.depends_on,
        )
        for item in todos
    ]
    deleted, created = await self.manager.write_todos(self.conversation_id, items)
    events: list[TodoEvent] = [TodoDeletedEvent(todo=todo) for todo in deleted]
    events += [TodoCreatedEvent(todo=todo) for todo in created]
    return (f"Wrote {len(created)} todos.", events)

add_todo async

add_todo(
    content: str, active_form: str
) -> tuple[str, list[TodoEvent]]

Append a single new todo (status pending).

Source code in octomate/mcp/todos.py
async def add_todo(
    self, content: str, active_form: str
) -> tuple[str, list[TodoEvent]]:
    """Append a single new todo (status pending)."""
    todo = await self.manager.add_todo(
        self.conversation_id, content=content, active_form=active_form
    )
    return (f"Added '{content}' (id: {todo.ref}).", [TodoCreatedEvent(todo=todo)])

update_todo_status async

update_todo_status(
    todo_id: str, status: TodoStatus
) -> str | tuple[str, list[TodoEvent]]

Change a todo's status by id.

Source code in octomate/mcp/todos.py
async def update_todo_status(
    self, todo_id: str, status: TodoStatus
) -> str | tuple[str, list[TodoEvent]]:
    """Change a todo's status by id."""
    conv = self.conversation_id
    previous = await self.manager.get_todo(conv, todo_id)
    if previous is None:
        return f"No todo with id '{todo_id}'."
    if status == "in_progress":
        if is_blocked(previous, by_ref(await self.manager.list_todos(conv))):
            return (
                f"Cannot start '{previous.content}' — it has incomplete "
                "dependencies."
            )
    updated = await self.manager.update_todo(conv, todo_id, status=status)
    if updated is None:
        return f"No todo with id '{todo_id}'."
    return (
        f"Updated '{updated.content}' → {status}.",
        update_events(updated, previous),
    )

remove_todo async

remove_todo(
    todo_id: str,
) -> str | tuple[str, list[TodoEvent]]

Delete a todo by id.

Source code in octomate/mcp/todos.py
async def remove_todo(self, todo_id: str) -> str | tuple[str, list[TodoEvent]]:
    """Delete a todo by id."""
    removed = await self.manager.remove_todo(self.conversation_id, todo_id)
    if removed is None:
        return f"No todo with id '{todo_id}'."
    return (f"Removed '{removed.content}'.", [TodoDeletedEvent(todo=removed)])

add_subtask async

add_subtask(
    parent_id: str, content: str, active_form: str
) -> str | tuple[str, list[TodoEvent]]

Add a subtask under an existing todo.

Source code in octomate/mcp/todos.py
async def add_subtask(
    self, parent_id: str, content: str, active_form: str
) -> str | tuple[str, list[TodoEvent]]:
    """Add a subtask under an existing todo."""
    conv = self.conversation_id
    parent = await self.manager.get_todo(conv, parent_id)
    if parent is None:
        return f"No parent todo with id '{parent_id}'."
    todo = await self.manager.add_todo(
        conv, content=content, active_form=active_form, parent_ref=parent_id
    )
    return (
        f"Added subtask '{content}' (id: {todo.ref}, parent: {parent_id}).",
        [TodoCreatedEvent(todo=todo)],
    )

set_dependency async

set_dependency(
    todo_id: str, depends_on_id: str
) -> str | tuple[str, list[TodoEvent]]

Make todo_id depend on depends_on_id (blocks it until that completes).

Source code in octomate/mcp/todos.py
async def set_dependency(
    self, todo_id: str, depends_on_id: str
) -> str | tuple[str, list[TodoEvent]]:
    """Make `todo_id` depend on `depends_on_id` (blocks it until that completes)."""
    conv = self.conversation_id
    todos = await self.manager.list_todos(conv)
    todos_by_ref = by_ref(todos)
    todo = todos_by_ref.get(todo_id)
    dependency = todos_by_ref.get(depends_on_id)
    if todo is None:
        return f"No todo with id '{todo_id}'."
    if dependency is None:
        return f"No todo with id '{depends_on_id}'."
    if todo_id == depends_on_id:
        return "A todo cannot depend on itself."
    if has_cycle(todos, todo_id, depends_on_id):
        return "Cannot add dependency: it would create a cycle."
    if depends_on_id in todo.depends_on:
        return "That dependency already exists."
    new_status: TodoStatus = todo.status
    if dependency.status != "completed" and todo.status not in (
        "completed",
        "blocked",
    ):
        new_status = "blocked"
    updated = await self.manager.update_todo(
        conv,
        todo_id,
        depends_on=[*todo.depends_on, depends_on_id],
        status=new_status,
    )
    if updated is None:
        return f"No todo with id '{todo_id}'."
    message = f"'{todo.content}' now depends on '{dependency.content}'."
    if new_status == "blocked" and todo.status != "blocked":
        message += " Task blocked until the dependency completes."
    return (message, update_events(updated, todo))

get_available_tasks async

get_available_tasks() -> str

List tasks with no incomplete dependencies (workable now).

Source code in octomate/mcp/todos.py
async def get_available_tasks(self) -> str:
    """List tasks with no incomplete dependencies (workable now)."""
    available = available_tasks(await self.manager.list_todos(self.conversation_id))
    if not available:
        return "No available tasks — all are completed or blocked."
    lines = ["Available tasks:"]
    for index, todo in enumerate(available, 1):
        marker = STATUS_MARKERS.get(todo.status, "[ ]")
        lines.append(f"{index}. {marker} [{todo.ref}] {todo.content}")
    return "\n".join(lines)

todo_instructions

todo_instructions() -> str
Source code in octomate/mcp/todos.py
def todo_instructions() -> str:
    return TODO_INSTRUCTION

by_ref

by_ref(todos: list[Todo]) -> dict[str, Todo]
Source code in octomate/mcp/todos.py
def by_ref(todos: list[Todo]) -> dict[str, Todo]:
    return {todo.ref: todo for todo in todos}

is_blocked

is_blocked(
    todo: Todo, todos_by_ref: dict[str, Todo]
) -> bool
Source code in octomate/mcp/todos.py
def is_blocked(todo: Todo, todos_by_ref: dict[str, Todo]) -> bool:
    return any(
        (dep := todos_by_ref.get(ref)) is not None and dep.status != "completed"
        for ref in todo.depends_on
    )

has_cycle

has_cycle(
    todos: list[Todo], todo_ref: str, depends_on_ref: str
) -> bool

Would making todo_ref depend on depends_on_ref create a cycle?

Source code in octomate/mcp/todos.py
def has_cycle(todos: list[Todo], todo_ref: str, depends_on_ref: str) -> bool:
    """Would making `todo_ref` depend on `depends_on_ref` create a cycle?"""
    todos_by_ref = by_ref(todos)
    visited: set[str] = set()

    def visit(current: str) -> bool:
        if current == todo_ref:
            return True
        if current in visited:
            return False
        visited.add(current)
        dep = todos_by_ref.get(current)
        if dep is None:
            return False
        return any(visit(ref) for ref in dep.depends_on)

    return visit(depends_on_ref)

available_tasks

available_tasks(todos: list[Todo]) -> list[Todo]
Source code in octomate/mcp/todos.py
def available_tasks(todos: list[Todo]) -> list[Todo]:
    todos_by_ref = by_ref(todos)
    return [
        todo
        for todo in todos
        if todo.status not in ("completed", "blocked")
        and not is_blocked(todo, todos_by_ref)
    ]

render_todos

render_todos(
    todos: list[Todo], *, hierarchical: bool
) -> str
Source code in octomate/mcp/todos.py
def render_todos(todos: list[Todo], *, hierarchical: bool) -> str:
    if hierarchical:
        children: dict[str | None, list[Todo]] = {}
        for todo in todos:
            children.setdefault(todo.parent_ref, []).append(todo)
        lines = ["Current todos (tree):"]
        counter = [0]

        def walk(parent: str | None, depth: int) -> None:
            for todo in children.get(parent, []):
                counter[0] += 1
                indent = "  " * depth
                marker = STATUS_MARKERS.get(todo.status, "[ ]")
                lines.append(
                    f"{indent}{counter[0]}. {marker} [{todo.ref}] {todo.content}"
                )
                if todo.depends_on:
                    lines.append(f"{indent}   depends on {', '.join(todo.depends_on)}")
                walk(todo.ref, depth + 1)

        walk(None, 0)
    else:
        lines = ["Current todos:"]
        for index, todo in enumerate(todos, 1):
            marker = STATUS_MARKERS.get(todo.status, "[ ]")
            lines.append(f"{index}. {marker} [{todo.ref}] {todo.content}")
            if todo.parent_ref:
                lines.append(f"   (subtask of {todo.parent_ref})")
            if todo.depends_on:
                lines.append(f"   (depends on {', '.join(todo.depends_on)})")

    counts = Counter(todo.status for todo in todos)
    summary = (
        f"\nSummary: {counts['completed']} completed, {counts['blocked']} blocked, "
        f"{counts['in_progress']} in progress, {counts['pending']} pending"
    )
    return "\n".join(lines) + summary

update_events

update_events(
    current: Todo, previous: Todo
) -> list[TodoEvent]
Source code in octomate/mcp/todos.py
def update_events(current: Todo, previous: Todo) -> list[TodoEvent]:
    events: list[TodoEvent] = [TodoUpdatedEvent(todo=current, previous=previous)]
    if current.status != previous.status:
        events.append(TodoStatusChangedEvent(todo=current, previous=previous))
        if current.status == "completed":
            events.append(TodoCompletedEvent(todo=current))
    return events

mount_todos

mount_todos(
    mcp: FastMCP,
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
) -> None

Derive the todo owner from the verified session, never tool arguments.

Source code in octomate/mcp/todos.py
def mount_todos(
    mcp: FastMCP, resolve_session: Callable[[], Awaitable[OctomateSession]]
) -> None:
    """Derive the todo owner from the verified session, never tool arguments."""

    def tools(session: OctomateSession) -> TodoTools:
        if session.conversation_id is None or session.conversation_address is None:
            raise ToolError("Todo tools require an active conversation.")
        return TodoTools(session.conversation_id)

    async def publish(
        session: OctomateSession, result: str | tuple[str, list[TodoEvent]]
    ) -> str:
        if isinstance(result, str):
            return result
        address = session.conversation_address
        if address is None:
            raise RuntimeError("A todo mutation has no conversation address")
        message, events = result
        for event in events:
            await session.publish(address, event)
        return message

    @mcp.tool(description=capability_contract(TodoTools.read_todos))
    async def read_todos(
        hierarchical: bool = False,
        # Depends declares injection; FastMCP resolves it separately for each call.
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await tools(session).read_todos(hierarchical)

    @mcp.tool(description=capability_contract(TodoTools.write_todos))
    async def write_todos(
        todos: list[TodoItem],
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(session, await tools(session).write_todos(todos))

    @mcp.tool(description=capability_contract(TodoTools.add_todo))
    async def add_todo(
        content: str,
        active_form: str,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(
            session, await tools(session).add_todo(content, active_form)
        )

    @mcp.tool(description=capability_contract(TodoTools.update_todo_status))
    async def update_todo_status(
        todo_id: str,
        status: TodoStatus,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(
            session, await tools(session).update_todo_status(todo_id, status)
        )

    @mcp.tool(description=capability_contract(TodoTools.remove_todo))
    async def remove_todo(
        todo_id: str,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(session, await tools(session).remove_todo(todo_id))

    @mcp.tool(description=capability_contract(TodoTools.add_subtask))
    async def add_subtask(
        parent_id: str,
        content: str,
        active_form: str,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(
            session, await tools(session).add_subtask(parent_id, content, active_form)
        )

    @mcp.tool(description=capability_contract(TodoTools.set_dependency))
    async def set_dependency(
        todo_id: str,
        depends_on_id: str,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await publish(
            session, await tools(session).set_dependency(todo_id, depends_on_id)
        )

    @mcp.tool(description=capability_contract(TodoTools.get_available_tasks))
    async def get_available_tasks(
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        return await tools(session).get_available_tasks()

octomate.tentacles.inkling.mcp

Inkling's core tools over the authenticated MCP endpoint.

json_object_adapter module-attribute

json_object_adapter = TypeAdapter(JsonObject)

Accomplices dataclass

The accomplices one stretch of a run called and has not heard back from.

Source code in octomate/tentacles/inkling/mcp.py
@dataclass
class Accomplices:
    """The accomplices one stretch of a run called and has not heard back from."""

    working: list[str] = field(default_factory=list)

    async def watch(
        self, stream: AsyncIterable[AgentStreamEvent]
    ) -> AsyncIterator[AgentStreamEvent]:
        """`stream` with each accomplice's start before its call and its finish
        before its result. One left unanswered finishes with the stretch: cancelled
        with it, or failed."""
        try:
            async for event in stream:
                lifecycle = self.observe(event)
                if lifecycle is not None:
                    # One dynamic-boundary cast: pydantic-ai types the stream as
                    # AgentStreamEvent, consumers match the concrete octomate event.
                    yield cast(AgentStreamEvent, lifecycle)
                yield event
        except (Exception, asyncio.CancelledError) as error:
            cancelled = isinstance(error, asyncio.CancelledError)
            for settled in self.abandon("cancelled" if cancelled else "failed"):
                yield settled
            raise
        for settled in self.abandon("failed"):
            yield settled

    def observe(
        self, event: AgentStreamEvent
    ) -> SubagentStartedEvent | SubagentSettledEvent | None:
        if isinstance(event, FunctionToolResultEvent):
            part = event.part
            if part.tool_call_id not in self.working:
                return None
            self.working.remove(part.tool_call_id)
            return SubagentSettledEvent(
                invocation_id=part.tool_call_id,
                status="completed" if part.outcome == "success" else "failed",
                response=part.model_response_str(),
            )
        if not isinstance(event, FunctionToolCallEvent) or event.part.tool_name not in {
            GatewayTool.COMMISSION,
            GatewayTool.WHISPER,
        }:
            return None
        name = event.part.args_as_dict().get("name")
        if not isinstance(name, str) or not name:
            # The spell refuses a nameless call, so no accomplice starts.
            return None
        self.working.append(event.part.tool_call_id)
        return SubagentStartedEvent(
            invocation_id=event.part.tool_call_id,
            kind="commission"
            if event.part.tool_name == GatewayTool.COMMISSION
            else "whisper",
            name=name,
        )

    def abandon(self, status: SubagentActivityStatus) -> list[AgentStreamEvent]:
        settled = [
            cast(
                AgentStreamEvent,
                SubagentSettledEvent(invocation_id=invocation_id, status=status),
            )
            for invocation_id in self.working
        ]
        self.working.clear()
        return settled

working class-attribute instance-attribute

working: list[str] = field(default_factory=list)

watch async

watch(
    stream: AsyncIterable[AgentStreamEvent],
) -> AsyncIterator[AgentStreamEvent]

stream with each accomplice's start before its call and its finish before its result. One left unanswered finishes with the stretch: cancelled with it, or failed.

Source code in octomate/tentacles/inkling/mcp.py
async def watch(
    self, stream: AsyncIterable[AgentStreamEvent]
) -> AsyncIterator[AgentStreamEvent]:
    """`stream` with each accomplice's start before its call and its finish
    before its result. One left unanswered finishes with the stretch: cancelled
    with it, or failed."""
    try:
        async for event in stream:
            lifecycle = self.observe(event)
            if lifecycle is not None:
                # One dynamic-boundary cast: pydantic-ai types the stream as
                # AgentStreamEvent, consumers match the concrete octomate event.
                yield cast(AgentStreamEvent, lifecycle)
            yield event
    except (Exception, asyncio.CancelledError) as error:
        cancelled = isinstance(error, asyncio.CancelledError)
        for settled in self.abandon("cancelled" if cancelled else "failed"):
            yield settled
        raise
    for settled in self.abandon("failed"):
        yield settled

observe

observe(
    event: AgentStreamEvent,
) -> SubagentStartedEvent | SubagentSettledEvent | None
Source code in octomate/tentacles/inkling/mcp.py
def observe(
    self, event: AgentStreamEvent
) -> SubagentStartedEvent | SubagentSettledEvent | None:
    if isinstance(event, FunctionToolResultEvent):
        part = event.part
        if part.tool_call_id not in self.working:
            return None
        self.working.remove(part.tool_call_id)
        return SubagentSettledEvent(
            invocation_id=part.tool_call_id,
            status="completed" if part.outcome == "success" else "failed",
            response=part.model_response_str(),
        )
    if not isinstance(event, FunctionToolCallEvent) or event.part.tool_name not in {
        GatewayTool.COMMISSION,
        GatewayTool.WHISPER,
    }:
        return None
    name = event.part.args_as_dict().get("name")
    if not isinstance(name, str) or not name:
        # The spell refuses a nameless call, so no accomplice starts.
        return None
    self.working.append(event.part.tool_call_id)
    return SubagentStartedEvent(
        invocation_id=event.part.tool_call_id,
        kind="commission"
        if event.part.tool_name == GatewayTool.COMMISSION
        else "whisper",
        name=name,
    )

abandon

abandon(
    status: SubagentActivityStatus,
) -> list[AgentStreamEvent]
Source code in octomate/tentacles/inkling/mcp.py
def abandon(self, status: SubagentActivityStatus) -> list[AgentStreamEvent]:
    settled = [
        cast(
            AgentStreamEvent,
            SubagentSettledEvent(invocation_id=invocation_id, status=status),
        )
        for invocation_id in self.working
    ]
    self.working.clear()
    return settled

OctomateTools

Bases: Toolset[None]

Preserve Inkling's approval, deferral and subagent display behavior over MCP.

Source code in octomate/tentacles/inkling/mcp.py
class OctomateTools(Toolset[None]):
    """Preserve Inkling's approval, deferral and subagent display behavior over MCP."""

    def get_instructions(self) -> str:
        return "\n".join(
            (
                gateway_instructions(lambda name: name),
                HANDOFF_INSTRUCTION,
                history_instructions(lambda name: name),
                todo_instructions(),
                tentacle_instructions(),
            )
        )

    async def wrap_run_event_stream(
        self,
        ctx: RunContext[None],
        *,
        stream: AsyncIterable[AgentStreamEvent],
    ) -> AsyncIterable[AgentStreamEvent]:
        async for event in Accomplices().watch(stream):
            yield event

    @staticmethod
    async def call(
        ctx: RunContext[None],
        call_tool: CallToolFunc,
        name: str,
        arguments: dict[str, JsonValue],
    ) -> McpToolResult:
        result = await call_tool(
            name,
            arguments,
            metadata={
                "tool_call_id": ctx.tool_call_id,
                "defer_teleport": name == gateway_tool(GatewayTool.TELEPORT),
            },
        )
        if name == gateway_tool(GatewayTool.TELEPORT):
            metadata = json_object_adapter.validate_python(result)
            if metadata.get("kind") != TELEPORT_DEFER_KIND:
                raise ValueError("The MCP gateway did not return a teleport deferral")
            raise CallDeferred(metadata=metadata)
        return result

    @classmethod
    def capabilities(cls, client: MCPToolset[None]) -> list[AgentCapability[None]]:
        """Keep the existing tool names and deferred discovery groups."""
        names = {
            **{name: gateway_tool(name) for name in GatewayTool},
            **{name: history_tool(name) for name in HISTORY_TOOLS},
        }
        tools = client.renamed(names)
        gateway = tools.filtered(lambda ctx, tool: tool.name in GatewayTool)
        return [
            cls(
                ApprovalRequiredToolset(
                    gateway,
                    approval_required_func=lambda ctx, tool, arguments: (
                        tool.name == GatewayTool.TELEPORT
                    ),
                ),
                id="gateway",
            ),
            Toolset(
                tools.filtered(lambda ctx, tool: tool.name in TODO_TOOL_NAMES),
                id="todos",
                description="Persisted task list for planning and tracking multi-step work.",
                defer_loading=True,
            ),
            Toolset(
                tools.filtered(lambda ctx, tool: tool.name in HISTORY_TOOLS),
                id="history",
                description="Search and page the current user's conversation history.",
                defer_loading=True,
            ),
            Toolset(
                tools.filtered(
                    lambda ctx, tool: tool.name not in {*names, *TODO_TOOL_NAMES}
                ),
                id="tentacles",
                description="The user's installed MCP tools and account linking.",
                defer_loading=True,
            ),
        ]

get_instructions

get_instructions() -> str
Source code in octomate/tentacles/inkling/mcp.py
def get_instructions(self) -> str:
    return "\n".join(
        (
            gateway_instructions(lambda name: name),
            HANDOFF_INSTRUCTION,
            history_instructions(lambda name: name),
            todo_instructions(),
            tentacle_instructions(),
        )
    )

wrap_run_event_stream async

wrap_run_event_stream(
    ctx: RunContext[None],
    *,
    stream: AsyncIterable[AgentStreamEvent],
) -> AsyncIterable[AgentStreamEvent]
Source code in octomate/tentacles/inkling/mcp.py
async def wrap_run_event_stream(
    self,
    ctx: RunContext[None],
    *,
    stream: AsyncIterable[AgentStreamEvent],
) -> AsyncIterable[AgentStreamEvent]:
    async for event in Accomplices().watch(stream):
        yield event

call async staticmethod

call(
    ctx: RunContext[None],
    call_tool: CallToolFunc,
    name: str,
    arguments: dict[str, JsonValue],
) -> McpToolResult
Source code in octomate/tentacles/inkling/mcp.py
@staticmethod
async def call(
    ctx: RunContext[None],
    call_tool: CallToolFunc,
    name: str,
    arguments: dict[str, JsonValue],
) -> McpToolResult:
    result = await call_tool(
        name,
        arguments,
        metadata={
            "tool_call_id": ctx.tool_call_id,
            "defer_teleport": name == gateway_tool(GatewayTool.TELEPORT),
        },
    )
    if name == gateway_tool(GatewayTool.TELEPORT):
        metadata = json_object_adapter.validate_python(result)
        if metadata.get("kind") != TELEPORT_DEFER_KIND:
            raise ValueError("The MCP gateway did not return a teleport deferral")
        raise CallDeferred(metadata=metadata)
    return result

capabilities classmethod

capabilities(
    client: MCPToolset[None],
) -> list[AgentCapability[None]]

Keep the existing tool names and deferred discovery groups.

Source code in octomate/tentacles/inkling/mcp.py
@classmethod
def capabilities(cls, client: MCPToolset[None]) -> list[AgentCapability[None]]:
    """Keep the existing tool names and deferred discovery groups."""
    names = {
        **{name: gateway_tool(name) for name in GatewayTool},
        **{name: history_tool(name) for name in HISTORY_TOOLS},
    }
    tools = client.renamed(names)
    gateway = tools.filtered(lambda ctx, tool: tool.name in GatewayTool)
    return [
        cls(
            ApprovalRequiredToolset(
                gateway,
                approval_required_func=lambda ctx, tool, arguments: (
                    tool.name == GatewayTool.TELEPORT
                ),
            ),
            id="gateway",
        ),
        Toolset(
            tools.filtered(lambda ctx, tool: tool.name in TODO_TOOL_NAMES),
            id="todos",
            description="Persisted task list for planning and tracking multi-step work.",
            defer_loading=True,
        ),
        Toolset(
            tools.filtered(lambda ctx, tool: tool.name in HISTORY_TOOLS),
            id="history",
            description="Search and page the current user's conversation history.",
            defer_loading=True,
        ),
        Toolset(
            tools.filtered(
                lambda ctx, tool: tool.name not in {*names, *TODO_TOOL_NAMES}
            ),
            id="tentacles",
            description="The user's installed MCP tools and account linking.",
            defer_loading=True,
        ),
    ]

octomate.mcp.history

The history tools as MCP: the thread ledger of the person a session speaks for, served beside the spells.

A family of its own on the one server, mounted under the history namespace. Every return is text and bounded — a page of at most HISTORY_PAGE_LIMIT messages, each clipped to HISTORY_LINE_CHARS — because these runtimes have none of the spill bands that catch an oversized return for Inkling.

HISTORY_LINE_CHARS module-attribute

HISTORY_LINE_CHARS = 400

HISTORY_PAGE_LIMIT module-attribute

HISTORY_PAGE_LIMIT = 50

HISTORY_TOOL_NAMES module-attribute

HISTORY_TOOL_NAMES: dict[str, str] = {
    "search_thread_history": "search",
    "read_thread_history_before": "read_before",
    "read_thread_history_after": "read_after",
}

mount_history

mount_history(
    mcp: FastMCP,
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
    thread_manager: ThreadManager,
) -> None

Register the history tools on mcp, every call reading as the person the session resolve_session returns speaks for — a driven turn's user, or the registered person a native session's bearer named.

Source code in octomate/mcp/history.py
def mount_history(
    mcp: FastMCP,
    resolve_session: Callable[[], Awaitable[OctomateSession]],
    thread_manager: ThreadManager,
) -> None:
    """Register the history tools on `mcp`, every call reading as the person the
    session `resolve_session` returns speaks for — a driven turn's user, or the
    registered person a native session's bearer named."""

    async def anchor(session: OctomateSession, handle: str) -> ThreadMessage:
        try:
            return await thread_manager.chat_message(session.user_profile, handle)
        except ValueError as refusal:
            raise ToolError(str(refusal), log_level=logging.INFO) from refusal

    def page(limit: int) -> int:
        if limit > HISTORY_PAGE_LIMIT:
            raise ToolError(
                f"limit {limit} is over the page of {HISTORY_PAGE_LIMIT}; page in "
                "smaller steps."
            )
        return limit

    @mcp.tool(
        name=HISTORY_TOOL_NAMES["search_thread_history"],
        description=capability_contract(HistoryCapability.search_thread_history),
        annotations={"readOnlyHint": True},
    )
    async def search_thread_history(
        query: str,
        actor_kind: ChannelActorKind | None = None,
        limit: int = 10,
        # Depends declares injection; FastMCP resolves it separately for each call.
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        try:
            rows = await thread_manager.search_chat_messages(
                session.user_profile, query, actor_kind=actor_kind, limit=page(limit)
            )
        except ValueError as refusal:
            raise ToolError(str(refusal), log_level=logging.INFO) from refusal
        return (
            "\n".join(
                line
                if len(line) <= HISTORY_LINE_CHARS
                else line[:HISTORY_LINE_CHARS] + "…"
                for line in map(str, rows)
            )
            or "(no messages)"
        )

    @mcp.tool(
        name=HISTORY_TOOL_NAMES["read_thread_history_before"],
        description=capability_contract(HistoryCapability.read_thread_history_before),
        annotations={"readOnlyHint": True},
    )
    async def read_thread_history_before(
        message_id: str,
        limit: int = 10,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        found = await anchor(session, message_id)
        rows = await thread_manager.chat_messages_before(
            found.thread_id, found.id, limit=page(limit)
        )
        return (
            "\n".join(
                line
                if len(line) <= HISTORY_LINE_CHARS
                else line[:HISTORY_LINE_CHARS] + "…"
                for line in map(str, rows)
            )
            or "(no messages)"
        )

    @mcp.tool(
        name=HISTORY_TOOL_NAMES["read_thread_history_after"],
        description=capability_contract(HistoryCapability.read_thread_history_after),
        annotations={"readOnlyHint": True},
    )
    async def read_thread_history_after(
        message_id: str,
        limit: int = 10,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        found = await anchor(session, message_id)
        rows = await thread_manager.chat_messages_after(
            found.thread_id, found.id, limit=page(limit)
        )
        return (
            "\n".join(
                line
                if len(line) <= HISTORY_LINE_CHARS
                else line[:HISTORY_LINE_CHARS] + "…"
                for line in map(str, rows)
            )
            or "(no messages)"
        )

octomate.mcp.oauth

Link the current channel profile and authorize the user's installed MCPs.

Authorization links and device codes go to the user's direct messages. The model receives status only; device flows finish through confirm.

OAUTH_NAMESPACE module-attribute

OAUTH_NAMESPACE = 'oauth'

CONNECT_TOOL module-attribute

CONNECT_TOOL = f'{OAUTH_NAMESPACE}_connect'

CONFIRM_TOOL module-attribute

CONFIRM_TOOL = f'{OAUTH_NAMESPACE}_confirm'
LINK_PROFILE_TOOL = f'{OAUTH_NAMESPACE}_link_profile'

ProviderId module-attribute

ProviderId = Annotated[
    str,
    Field(
        description="The user's installed MCP namespace."
    ),
]

mount_oauth

mount_oauth(
    mcp: FastMCP,
    resolve_session: Callable[
        [], Awaitable[OctomateSession]
    ],
    manager: McpManager,
    *,
    resolve_owner: Callable[[], Awaitable[User]],
) -> None

Link profiles and authorize MCPs for the person driving the current turn.

Source code in octomate/mcp/oauth.py
def mount_oauth(
    mcp: FastMCP,
    resolve_session: Callable[[], Awaitable[OctomateSession]],
    manager: McpManager,
    *,
    resolve_owner: Callable[[], Awaitable[User]],
) -> None:
    """Link profiles and authorize MCPs for the person driving the current turn."""

    async def personal(provider: str, user: User) -> OAuthMcp:
        try:
            return await manager.authorizable(user_id=user.id, namespace=provider)
        except McpUnavailable as error:
            raise ToolError("This OAuth MCP is unavailable") from error

    @mcp.tool(
        name="connect",
        description=(
            "Send this user a link that authorizes their own account with a "
            "provider identified by its installed MCP namespace. The link, and a code where the provider asks "
            "for one, go to their direct messages, never to the conversation, and "
            "are not returned here."
        ),
    )
    async def connect(
        provider: ProviderId,
        # Depends declares injection; FastMCP resolves it separately for each call.
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
        user: User = Depends(resolve_owner),  # noqa: B008
        *,
        flow: OAuthFlowKind | None = None,
    ) -> str:
        profile = session.user_profile
        address = session.conversation_address
        channel = (
            session.channels.get(address.channel_tentacle_id)
            if address is not None
            else None
        )
        if address is None or channel is None:
            raise ToolError(
                "The link goes to the person's direct messages on the channel "
                "this turn is on, and this call has no turn on a channel."
            )
        instance = await personal(provider, user)
        try:
            authorization = await manager.connect(
                user, instance.id, profile=profile, flow=flow
            )
        except McpUnavailable as error:
            raise ToolError(str(error)) from error
        label = instance.name
        # The authorization goes to the channel as an event of its own, for the
        # channel to present — never through this return value, which the model
        # reads and could repeat into a reply.
        if isinstance(authorization, AuthorizationLink):
            event = OAuthAuthorizationEvent(
                connector_id=provider,
                label=label,
                authorization_uri=str(authorization.authorization_uri),
            )
            sent = "The authorization link is on its way"
        else:
            event = OAuthDeviceAuthorizationEvent(
                connector_id=provider,
                label=label,
                authorization_uri=str(
                    authorization.verification_uri_complete
                    or authorization.verification_uri
                ),
                user_code=authorization.user_code.get_secret_value(),
            )
            sent = "The authorization link and code are on their way"
        # Settled here, so the link is heard only where the channel will show it.
        private = await channel.feelers.oauth.deliver_to(address)
        await session.publish(private, event, private=True)
        return f"{sent} to this user's direct messages."

    @mcp.tool(
        name="confirm",
        description="Check authorization for a user's installed MCP namespace, polling when required.",
    )
    async def confirm(
        provider: ProviderId,
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
        user: User = Depends(resolve_owner),  # noqa: B008
    ) -> str:
        profile = session.user_profile
        instance = await personal(provider, user)
        status = await manager.confirm(user, instance.id, profile=profile)
        match status:
            case McpAuthorizationStatus(status="active"):
                return f"{provider} is connected and available through namespace discovery."
            case McpDeviceAuthorizationPending(retry_after_seconds=delay):
                return f"{provider} is waiting for approval; confirm again in {delay} seconds."
            case McpBrowserAuthorizationPending():
                return f"{provider} is waiting for approval in the browser. Confirm after approval."
            case _:
                return f"{provider} needs authorization. Call `{CONNECT_TOOL}` with `{provider}`."

    @mcp.tool(
        name="link_profile",
        description=(
            "Request authorization from the Octomate host to link the channel profile "
            "driving this turn to the signed-in user's account. The host authorization "
            "card is sent privately through the channel. Use this when the "
            "user asks to link their current channel profile. The profile and "
            "destination come from the current turn, never tool arguments; the "
            "link goes to that user's direct messages and is not returned here. "
            "Trunkline already uses the signed-in Octomate identity and cannot link profiles."
        ),
    )
    async def link_profile(
        session: OctomateSession = Depends(resolve_session),  # noqa: B008
    ) -> str:
        # Trunkline's routers import Octomate, which mounts this MCP module.
        from octomate.tentacles.trunkline.base import TrunklineTentacle

        profile = session.user_profile
        address = session.conversation_address
        channel = (
            session.channels.get(address.channel_tentacle_id)
            if address is not None
            else None
        )
        if isinstance(channel, TrunklineTentacle):
            raise ToolError(
                "Trunkline already uses your signed-in Octomate identity; "
                "profile linking is not needed."
            )
        if address is None or channel is None:
            raise ToolError(
                "Linking a profile requires a turn from a user on a channel."
            )
        if (
            profile.channel_tentacle_id != address.channel_tentacle_id
            or profile.channel_user_id != address.user_id
        ):
            raise ToolError(
                "The current channel profile does not match the user who drove this turn."
            )
        try:
            private_address = await channel.feelers.oauth.deliver_to(address)
        except RuntimeError as error:
            raise ToolError(
                "This channel has no private surface for a profile link."
            ) from error
        try:
            authorization = await manager.users.start_link_profile(profile)
        except (
            InvalidLinkProfile,
            ProfileAlreadyLinked,
            LinkProfileUnavailable,
        ) as error:
            raise ToolError(str(error)) from error
        message_id = await channel.feelers.oauth.present(
            private_address,
            LinkProfileAuthorizationEvent(
                host=channel.octomate.title,
                authorization=authorization,
            ),
        )
        if message_id is None:
            raise ToolError("The channel could not deliver the private profile link.")
        return "The profile link was sent privately to this user."

octomate.mcp.base

What every Octomate MCP server shares: the bearer verifier for API keys and OAuth tokens, and the docstring projection that keeps a spell's MCP tool and its Inkling tool identical.

OCTOMATE_SERVER_NAME module-attribute

OCTOMATE_SERVER_NAME = 'octomate'

OCTOMATE_MCP_PATH module-attribute

OCTOMATE_MCP_PATH = f'/{OCTOMATE_SERVER_NAME}/mcp'

KnownBearers

Bases: TokenVerifier

Verify API keys and resource-bound OAuth tokens through the auth manager.

Source code in octomate/mcp/base.py
class KnownBearers(TokenVerifier):
    """Verify API keys and resource-bound OAuth tokens through the auth manager."""

    def __init__(self, auth: AuthManager | None = None, *, users: UserManager) -> None:
        super().__init__(required_scopes=["mcp"])
        self.auth: AuthManager | None = auth
        self.users: UserManager = users

    async def owner(self, token: str, *, scope: ApiKeyScope) -> str | None:
        principal = await self.verify_token(token, scope=scope)
        return principal.subject if principal is not None else None

    async def verify_token(
        self, token: str, *, scope: ApiKeyScope = "mcp"
    ) -> AccessToken | None:
        if self.auth is None:
            return None
        key = await self.auth.authenticate_api_key(SecretStr(token), scope=scope)
        if key is not None:
            user = await self.users.get(key.user_id)
            if user is None:
                return None
            return AccessToken(
                token=token,
                client_id=user.username,
                subject=user.username,
                scopes=[scope],
            )
        if self.auth.config.oauth_issuer_url is None:
            return None
        issuer = str(self.auth.config.oauth_issuer_url).rstrip("/")
        resource_path = OCTOMATE_MCP_PATH if scope == "mcp" else "/api"
        principal = await self.auth.authenticate_oauth_token(
            SecretStr(token), resource=f"{issuer}{resource_path}", scope=scope
        )
        if principal is None:
            return None
        user = await self.users.get(principal.user_id)
        if user is None:
            return None
        return AccessToken(
            token=token,
            client_id=str(principal.client_id),
            subject=user.username,
            scopes=list(principal.scopes),
            expires_at=int(principal.expires_at.timestamp()),
            resource=principal.resource,
            claims={"iss": str(self.auth.config.oauth_issuer_url)},
        )

auth instance-attribute

auth: AuthManager | None = auth

users instance-attribute

users: UserManager = users

owner async

owner(token: str, *, scope: ApiKeyScope) -> str | None
Source code in octomate/mcp/base.py
async def owner(self, token: str, *, scope: ApiKeyScope) -> str | None:
    principal = await self.verify_token(token, scope=scope)
    return principal.subject if principal is not None else None

verify_token async

verify_token(
    token: str, *, scope: ApiKeyScope = "mcp"
) -> AccessToken | None
Source code in octomate/mcp/base.py
async def verify_token(
    self, token: str, *, scope: ApiKeyScope = "mcp"
) -> AccessToken | None:
    if self.auth is None:
        return None
    key = await self.auth.authenticate_api_key(SecretStr(token), scope=scope)
    if key is not None:
        user = await self.users.get(key.user_id)
        if user is None:
            return None
        return AccessToken(
            token=token,
            client_id=user.username,
            subject=user.username,
            scopes=[scope],
        )
    if self.auth.config.oauth_issuer_url is None:
        return None
    issuer = str(self.auth.config.oauth_issuer_url).rstrip("/")
    resource_path = OCTOMATE_MCP_PATH if scope == "mcp" else "/api"
    principal = await self.auth.authenticate_oauth_token(
        SecretStr(token), resource=f"{issuer}{resource_path}", scope=scope
    )
    if principal is None:
        return None
    user = await self.users.get(principal.user_id)
    if user is None:
        return None
    return AccessToken(
        token=token,
        client_id=str(principal.client_id),
        subject=user.username,
        scopes=list(principal.scopes),
        expires_at=int(principal.expires_at.timestamp()),
        resource=principal.resource,
        claims={"iss": str(self.auth.config.oauth_issuer_url)},
    )

capability_contract

capability_contract(
    spell: Callable[..., Awaitable[object]],
) -> str

The docstring Inkling's toolset compiles, verbatim — a copy here would give two models two different tools and drift silently.

Source code in octomate/mcp/base.py
def capability_contract(spell: Callable[..., Awaitable[object]]) -> str:
    """The docstring Inkling's toolset compiles, verbatim — a copy here would give
    two models two different tools and drift silently."""
    doc = spell.__doc__
    if doc is None:
        raise RuntimeError(f"{spell.__qualname__} has no docstring to project")
    return cleandoc(doc)

octomate.mcp.transport

An httpx transport for MCP endpoints that connects only to public addresses and refuses redirects.

IP_ADDRESSES module-attribute

IP_ADDRESSES = TypeAdapter(list[IPvAnyAddress])

PublicMcpNetwork

Bases: AnyIOBackend

Resolve and pin each connection to a public address, including reconnects.

Source code in octomate/mcp/transport.py
class PublicMcpNetwork(AnyIOBackend):
    """Resolve and pin each connection to a public address, including reconnects."""

    async def connect_tcp(
        self,
        host: str,
        port: int,
        # httpcore's backend contract requires this parameter.
        timeout: float | None = None,  # noqa: ASYNC109
        local_address: str | None = None,
        socket_options: Iterable[SOCKET_OPTION] | None = None,
    ) -> AsyncNetworkStream:
        async with asyncio.timeout(timeout):
            addresses = await asyncio.get_running_loop().getaddrinfo(
                host=host, port=port, type=socket.SOCK_STREAM
            )
            ips = IP_ADDRESSES.validate_python([address[4][0] for address in addresses])
            if not ips or any(not ip.is_global or ip.is_multicast for ip in ips):
                raise ConnectError(
                    "MCP endpoints must resolve only to public addresses"
                )
            # Pass the checked numeric address to the socket layer; TLS still uses
            # the original hostname held by httpcore's connection.
            return await super().connect_tcp(
                host=str(addresses[0][4][0]),
                port=port,
                timeout=timeout,
                local_address=local_address,
                socket_options=socket_options,
            )

connect_tcp async

connect_tcp(
    host: str,
    port: int,
    timeout: float | None = None,
    local_address: str | None = None,
    socket_options: Iterable[SOCKET_OPTION] | None = None,
) -> AsyncNetworkStream
Source code in octomate/mcp/transport.py
async def connect_tcp(
    self,
    host: str,
    port: int,
    # httpcore's backend contract requires this parameter.
    timeout: float | None = None,  # noqa: ASYNC109
    local_address: str | None = None,
    socket_options: Iterable[SOCKET_OPTION] | None = None,
) -> AsyncNetworkStream:
    async with asyncio.timeout(timeout):
        addresses = await asyncio.get_running_loop().getaddrinfo(
            host=host, port=port, type=socket.SOCK_STREAM
        )
        ips = IP_ADDRESSES.validate_python([address[4][0] for address in addresses])
        if not ips or any(not ip.is_global or ip.is_multicast for ip in ips):
            raise ConnectError(
                "MCP endpoints must resolve only to public addresses"
            )
        # Pass the checked numeric address to the socket layer; TLS still uses
        # the original hostname held by httpcore's connection.
        return await super().connect_tcp(
            host=str(addresses[0][4][0]),
            port=port,
            timeout=timeout,
            local_address=local_address,
            socket_options=socket_options,
        )

PublicMcpTransport

Bases: AsyncHTTPTransport

Source code in octomate/mcp/transport.py
class PublicMcpTransport(httpx2.AsyncHTTPTransport):
    def __init__(self) -> None:
        # HTTPX exposes no network-backend argument. Keep its request/response
        # adapter and supply the httpcore pool at this one dependency boundary.
        self._pool = AsyncConnectionPool(
            ssl_context=ssl.create_default_context(),
            network_backend=PublicMcpNetwork(),
        )

    async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
        response = await super().handle_async_request(request)
        if response.has_redirect_location:
            await response.aclose()
            raise httpx2.HTTPStatusError(
                "Install the final MCP endpoint URL; redirects are not allowed",
                request=request,
                response=response,
            )
        return response

handle_async_request async

handle_async_request(request: Request) -> httpx2.Response
Source code in octomate/mcp/transport.py
async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
    response = await super().handle_async_request(request)
    if response.has_redirect_location:
        await response.aclose()
        raise httpx2.HTTPStatusError(
            "Install the final MCP endpoint URL; redirects are not allowed",
            request=request,
            response=response,
        )
    return response

mcp_http_client

mcp_http_client(
    headers: dict[str, str] | None = None,
    timeout: Timeout | None = None,
    auth: Auth | None = None,
    follow_redirects: bool = False,
) -> httpx2.AsyncClient
Source code in octomate/mcp/transport.py
def mcp_http_client(
    headers: dict[str, str] | None = None,
    timeout: httpx2.Timeout | None = None,
    auth: httpx2.Auth | None = None,
    follow_redirects: bool = False,
) -> httpx2.AsyncClient:
    return httpx2.AsyncClient(
        headers=headers,
        timeout=timeout or httpx2.Timeout(30),
        auth=auth,
        transport=PublicMcpTransport(),
        trust_env=False,
        # A redirect must never carry an instance's credential to another
        # endpoint. Users install the final MCP URL explicitly.
        follow_redirects=False,
    )

octomate.mcp.routes

The HTTP API for a user's MCP installations: listing, installing, authorizing, enabling and removing them.

logger module-attribute

logger = logging.getLogger(__name__)

mcp_router module-attribute

mcp_router = APIRouter(
    prefix="/api/mcp",
    tags=["mcp"],
    dependencies=[Depends(browser_request)],
)

available_tentacles async

available_tentacles(
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> list[McpTentacleInfo]
Source code in octomate/mcp/routes.py
@mcp_router.get("/tentacles", response_model=list[McpTentacleInfo])
async def available_tentacles(
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> list[McpTentacleInfo]:
    return manager.available()

list_instances async

list_instances(
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> list[Mcp]
Source code in octomate/mcp/routes.py
@mcp_router.get("", response_model=list[McpVariant])
async def list_instances(
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> list[Mcp]:
    return await manager.list(user.id)

install async

install(
    body: McpInstallRequest,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp
Source code in octomate/mcp/routes.py
@mcp_router.post("", status_code=201, response_model=McpVariant)
async def install(
    body: McpInstallRequest,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp:
    try:
        return await manager.install(user.id, body)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error

pending_authorization async

pending_authorization(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> JSONResponse
Source code in octomate/mcp/routes.py
@mcp_router.get("/{mcp_id}/authorization", response_model=OAuthStartResult | None)
async def pending_authorization(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> JSONResponse:
    try:
        authorization = await manager.pending_authorization(user, mcp_id)
        content = (
            authorization.model_dump(mode="json") if authorization is not None else None
        )
        if isinstance(authorization, DeviceAuthorization):
            assert content is not None
            content["user_code"] = authorization.user_code.get_secret_value()
        return JSONResponse(content=content, headers={"Cache-Control": "no-store"})
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error
    except ValueError as error:
        raise HTTPException(
            status_code=400, detail="Pending MCP authorization could not be restored"
        ) from error

cancel_authorization async

cancel_authorization(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> None
Source code in octomate/mcp/routes.py
@mcp_router.delete("/{mcp_id}/authorization", status_code=204)
async def cancel_authorization(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> None:
    try:
        await manager.cancel_authorization(user, mcp_id)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error

connect async

connect(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
    flow: OAuthFlowKind | None = None,
) -> JSONResponse
Source code in octomate/mcp/routes.py
@mcp_router.post("/{mcp_id}/connect", response_model=OAuthStartResult)
async def connect(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
    flow: OAuthFlowKind | None = None,
) -> JSONResponse:
    try:
        authorization = await manager.connect(user, mcp_id, flow=flow)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error
    except (ValueError, httpx2.HTTPError, OAuthFlowError) as error:
        logger.warning("Failed to authorize MCP %s (%s)", mcp_id, type(error).__name__)
        raise HTTPException(
            status_code=400, detail="MCP authorization could not be started"
        ) from error
    content = authorization.model_dump(mode="json")
    if isinstance(authorization, DeviceAuthorization):
        content["user_code"] = authorization.user_code.get_secret_value()
    return JSONResponse(content=content, headers={"Cache-Control": "no-store"})

confirm async

confirm(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> McpAuthorizationResult
Source code in octomate/mcp/routes.py
@mcp_router.post("/{mcp_id}/confirm", response_model=McpAuthorizationResult)
async def confirm(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> McpAuthorizationResult:
    try:
        return await manager.confirm(user, mcp_id)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error
    except (ValueError, httpx2.HTTPError, OAuthFlowError) as error:
        logger.warning("Failed to confirm MCP %s (%s)", mcp_id, type(error).__name__)
        raise HTTPException(
            status_code=400, detail="MCP authorization could not be confirmed"
        ) from error

enable async

enable(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp
Source code in octomate/mcp/routes.py
@mcp_router.post("/{mcp_id}/enable", response_model=McpVariant)
async def enable(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp:
    try:
        return await manager.enable(user_id=user.id, mcp_id=mcp_id)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error

disable async

disable(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp
Source code in octomate/mcp/routes.py
@mcp_router.post("/{mcp_id}/disable", response_model=McpVariant)
async def disable(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> Mcp:
    try:
        return await manager.disable(user_id=user.id, mcp_id=mcp_id)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error

uninstall async

uninstall(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> None
Source code in octomate/mcp/routes.py
@mcp_router.delete("/{mcp_id}", status_code=204)
async def uninstall(
    mcp_id: UUID7,
    user: Annotated[User, Depends(current_user)],
    manager: Annotated[McpManager, Depends(mcp_manager)],
) -> None:
    try:
        await manager.uninstall(user.id, mcp_id)
    except McpUnavailable as error:
        raise HTTPException(status_code=404, detail=str(error)) from error