# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-confused-deputy-escalation-when-an-mcp-server-reuses-a-single-transport-level-bearer-token-across-per-tool-consent-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-confused-deputy-escalation-when-an-mcp-server-reuses-a-single-transport-level-bearer-token-across-per-tool-consent-scope.warrant.json
# Markdown SHA-256:   56727ecbde64cf91b087503aa5b0704df67beb97d1956393b43e84082ccc18b4
# Code AST SHA-256:   43d9d3079d475b5164ea1fd8b49f1e6bbf4a784f89f54c861e4035b504b9ef9d
# Verified Classes:   ConfusedDeputyScopeError, ToolRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConfusedDeputyScopeError(RuntimeError):
    """Raised when a tool call's required scope is not in the session consent grant."""
    pass


class ToolRegistry:
    def __init__(self):
        # tool name -> required consent scope
        self._scopes = {
            "search_docs": "docs:read",
            "write_file": "fs:write",
            "send_email": "mail:send",
        }

    def required_scope(self, tool: str) -> str:
        if tool not in self._scopes:
            raise ConfusedDeputyScopeError(f"unknown tool {tool!r}")
        return self._scopes[tool]

    def manifest_for(self, consent: set[str]) -> list[str]:
        # Capability advertisement MUST be filtered by the consent grant.
        return [t for t, s in self._scopes.items() if s in consent]


def dispatch(session_consent: set[str], tool: str, args: dict) -> dict:
    """Authorize at tool-dispatch against the session consent grant.

    Transport authentication already happened; it must NOT be reused here.
    """
    registry = ToolRegistry()
    required = registry.required_scope(tool)
    if required not in session_consent:
        # The confused-deputy stop: valid session, insufficient per-tool consent.
        raise ConfusedDeputyScopeError(
            f"tool {tool!r} requires scope {required!r}; "
            f"session holds {sorted(session_consent)}"
        )
    return {"tool": tool, "status": "executed", "args": args}


# Trace: agent holds docs:read only, but manifest leaked write_file and the
# reasoning loop selected it. Flat-auth would execute; scoped dispatch refuses.
session = {"docs:read"}
try:
    dispatch(session, "write_file", {"path": "/etc/app.conf", "data": "..."})
except ConfusedDeputyScopeError as e:
    print(f"DENIED insufficient_scope: {e}")
