Commit Graph

1 Commits

  • Python: [BREAKING] Add sampling guardrails to MCP tools (#6413)
    * Add sampling guardrails to MCP tools
    
    Add approval, token, and request-count controls to the MCP sampling
    callback used when an MCPTool is configured with a chat client.
    
    - Add `sampling_approval_callback`, `sampling_max_tokens`, and
      `sampling_max_requests` parameters to `MCPTool` and its
      `MCPStdioTool`, `MCPStreamableHTTPTool`, and `MCPWebsocketTool`
      subclasses, positioned directly after `client`.
    - Gate each server-initiated `sampling/createMessage` request behind the
      approval callback, which denies by default when no callback is provided.
    - Clamp the requested `maxTokens` to `sampling_max_tokens` and enforce a
      per-session request count via `sampling_max_requests`.
    - Log incoming sampling requests at WARNING level (counts only).
    - Export `SamplingApprovalCallback` from the public API.
    - Add tests, a sample, and documentation updates.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    * Make sampling denial message context-aware
    
    Distinguish the deny-by-default case (no approval callback configured)
    from an explicit denial by a configured `sampling_approval_callback`, so
    the returned ErrorData message is accurate for callback-driven denials
    and exceptions.
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>