Addressed PR comments.

This commit is contained in:
Peter Ibekwe
2026-05-21 16:02:01 -07:00
Unverified
parent e642371a20
commit 41eac64ee3
9 changed files with 690 additions and 284 deletions
@@ -0,0 +1 @@
# Copyright (c) Microsoft. All rights reserved.
@@ -11,35 +11,32 @@ tools (e.g. ``web_search``) returns the tool under its plain name.
This sample mirrors the .NET sample
``dotnet/samples/03-workflows/Declarative/InvokeFoundryToolboxMcp/`` and
shows how to:
focuses on the **workflow execution path**:
1. Provision a toolbox in a Foundry project (delete-then-create_version,
so the sample can be re-run without manual cleanup).
2. Configure a ``WorkflowFactory`` with a custom :class:`MCPToolHandler`
that:
* routes every MCP request through a single
:class:`httpx.AsyncClient` carrying an Azure AD bearer token
(the toolbox endpoint requires AAD auth), and
* intercepts the reserved tool name ``"tools/list"`` so the YAML
can introspect the toolbox tool set without an extra Python
round-trip (matching the .NET ``DefaultMcpToolHandler``
behaviour).
3. Invoke ``microsoft_docs_search`` (from the Microsoft Learn Docs MCP
server surfaced by the toolbox) and ``web_search`` (Foundry built-in)
from a single declarative workflow.
4. Hand both result sets to a local :class:`Agent` registered with the
factory by name so the workflow's ``InvokeAzureAgent`` action can
summarise them.
1. Build a bearer-authenticated ``httpx.AsyncClient`` for the toolbox
MCP proxy and hand it to :class:`DefaultMCPToolHandler` so the YAML
can call MCP tools (and introspect the toolbox tool list via the
reserved ``"tools/list"`` tool name handled natively by the
framework, matching .NET
``DefaultMcpToolHandler.ListToolsToolName``).
2. Configure a :class:`WorkflowFactory` with that handler plus a local
:class:`Agent` registered by name so the YAML's ``InvokeAzureAgent``
action can summarise the combined tool output.
3. Drive the workflow with a user question and render per-action
progress markers plus the final agent summary.
One-off **toolbox administration** (delete + create_version) is delegated
to :mod:`toolbox_provisioning` so this file stays focused on the workflow.
Security note:
The default ``DefaultMCPToolHandler`` performs no URL allowlisting or
SSRF protection. This sample wraps it with a project-scoped handler
SSRF protection. This sample uses a project-scoped ``client_provider``
that pins outbound requests to ``Authorization: Bearer …`` via Azure
AD; for production deployments, additionally constrain the workflow
YAML to a known toolbox URL and reject any other server URL before
delegating to the inner handler. MCP outputs flow back into agent
conversations and share the prompt-injection risk surface of any
other tool output.
AD AND fails closed (raises) when the YAML resolves a different
``serverUrl``, so a tampered ``=Env.*`` value cannot redirect the
bearer token to an attacker-controlled URL. MCP outputs flow back
into agent conversations and share the prompt-injection risk
surface of any other tool output.
Run with:
python samples/03-workflows/declarative/invoke_foundry_toolbox_mcp/main.py
@@ -90,31 +87,31 @@ Sample output:
"""
import asyncio
import contextlib
import json
import os
import sys
from collections.abc import Iterator
from pathlib import Path
from typing import Any
import httpx
from agent_framework import Agent, Content, MCPStreamableHTTPTool
from agent_framework import Agent
from agent_framework.declarative import (
DefaultMCPToolHandler,
MCPToolInvocation,
MCPToolResult,
WorkflowFactory,
)
from agent_framework.foundry import FoundryChatClient
from azure.core.credentials import TokenCredential
from azure.identity import AzureCliCredential, get_bearer_token_provider
from toolbox_provisioning import (
AZ_CLI_PROCESS_TIMEOUT_SECONDS,
FOUNDRY_FEATURES_HEADERS,
build_toolbox_mcp_server_url,
create_sample_toolbox,
)
DEFAULT_TOOLBOX_NAME = "declarative_foundry_toolbox_mcp"
DEFAULT_TOOLBOX_API_VERSION = "v1"
DEFAULT_DOCS_SERVER_LABEL = "microsoft_docs"
DEFAULT_WEB_SEARCH_TOOL_NAME = "web_search"
DEFAULT_DOCS_MCP_SERVER_URL = "https://learn.microsoft.com/api/mcp"
AGENT_NAME = "FoundryToolboxMcpAgent"
@@ -133,38 +130,10 @@ _ACTION_PROGRESS_LABELS: dict[str, str] = {
SUMMARIZE_ACTION_ID: "Summarizing results...",
}
# Reserved tool name that the YAML uses to ask the handler for the toolbox
# tool list. Mirrors .NET ``DefaultMcpToolHandler.ListToolsToolName``.
LIST_TOOLS_TOOL_NAME = "tools/list"
# AAD audience for the toolbox MCP proxy. Same scope used by the existing
# Foundry hosted-toolbox samples.
TOOLBOX_AAD_SCOPE = "https://ai.azure.com/.default"
# Toolbox administration is gated by an Azure AI Foundry preview feature
# flag. The .NET sample injects this header via a pipeline policy on the
# ``AgentAdministrationClient``; the Python ``AIProjectClient`` doesn't
# add it automatically, so we pass it as a per-call header on every
# toolbox admin operation (delete + create_version) to make sure the
# toolbox is actually provisioned in the V1Preview routing path that the
# MCP proxy serves. Without this header, the calls can succeed at the
# HTTP layer but the toolbox is never wired up to the MCP endpoint —
# which surfaces at runtime as "MCP server failed to initialize:
# Session terminated" on the first ``InvokeMcpTool`` call.
FOUNDRY_FEATURES_HEADER_NAME = "Foundry-Features"
FOUNDRY_FEATURES_HEADER_VALUE = "Toolboxes=V1Preview"
FOUNDRY_FEATURES_HEADERS: dict[str, str] = {
FOUNDRY_FEATURES_HEADER_NAME: FOUNDRY_FEATURES_HEADER_VALUE,
}
# Bump the ``az.cmd`` subprocess timeout from the default 10s. On Windows
# the Azure CLI batch wrapper can take noticeably longer than 10s to
# return a token (cold-start + ``az`` self-update checks + AAD round-trip),
# which surfaces as ``CredentialUnavailableError: Failed to invoke the
# Azure CLI`` after a ``subprocess.TimeoutExpired`` from the credential's
# internal call.
AZ_CLI_PROCESS_TIMEOUT_SECONDS = 60
# Match the MCP-recommended httpx timeouts (``mcp.shared._httpx_utils``:
# 30s connect/write/pool, 5min SSE read). httpx's default ``Timeout(5.0)``
# is far too aggressive for MCP streaming responses — long-running
@@ -189,70 +158,6 @@ result set contains an answer, say so plainly rather than guessing.
"""
def build_toolbox_mcp_server_url(project_endpoint: str, name: str, api_version: str) -> str:
"""Compose the Foundry toolbox MCP proxy URL.
Toolboxes provisioned via ``AIProjectClient.beta.toolboxes`` live under
the ``/toolboxes/{name}`` resource path (the Python SDK's
``BetaToolboxesOperations`` routes POST/GET/DELETE there — see
``azure/ai/projects/operations/_operations.py``). Their MCP proxy URL
is ``<project_endpoint>/toolboxes/{name}/mcp?api-version=<api_version>``,
matching the .NET sample.
"""
base = project_endpoint.rstrip("/")
return f"{base}/toolboxes/{name}/mcp?api-version={api_version}"
def create_sample_toolbox(
*,
name: str,
docs_server_label: str,
project_endpoint: str,
docs_server_url: str = DEFAULT_DOCS_MCP_SERVER_URL,
) -> None:
"""Provision a toolbox version in the Foundry project (idempotent).
Toolboxes are normally provisioned through the Foundry portal or a
deployment script; this helper exists so the sample can be re-run
end-to-end without manual cleanup. It deletes any toolbox under
``name`` and then creates a new version that bundles:
- the Microsoft Learn Docs MCP server (``server_label=docs_server_label``),
and
- the Foundry built-in ``web_search`` tool.
"""
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPTool, Tool, WebSearchTool
from azure.core.exceptions import ResourceNotFoundError
with (
AzureCliCredential(process_timeout=AZ_CLI_PROCESS_TIMEOUT_SECONDS) as credential,
AIProjectClient(credential=credential, endpoint=project_endpoint) as project_client,
):
try:
project_client.beta.toolboxes.delete(name, headers=FOUNDRY_FEATURES_HEADERS)
print(f"Toolbox '{name}' deleted (replacing with a fresh version).")
except ResourceNotFoundError:
pass
tools: list[Tool] = [
MCPTool(
server_label=docs_server_label,
server_url=docs_server_url,
require_approval="never",
),
WebSearchTool(),
]
created = project_client.beta.toolboxes.create_version(
name=name,
description="Sample toolbox combining Microsoft Learn Docs MCP and Foundry web search.",
tools=tools,
headers=FOUNDRY_FEATURES_HEADERS,
)
print(f"Created toolbox {created.name}@{created.version} ({len(created.tools)} tool(s)).")
class _BearerAuth(httpx.Auth):
"""Inject a fresh Azure AD bearer token on every request.
@@ -269,94 +174,6 @@ class _BearerAuth(httpx.Auth):
yield request
class _ToolboxMcpToolHandler:
""":class:`MCPToolHandler` that adds ``tools/list`` support to the default handler.
The reserved tool name ``"tools/list"`` is intercepted client-side: it
is translated to an MCP ``session.list_tools()`` call and the result
is returned as a single JSON-encoded ``TextContent`` matching the
shape produced by the .NET ``DefaultMcpToolHandler``
(``{"tools": [{name, description, inputSchema, outputSchema}]}``).
All other tool invocations delegate to the wrapped
:class:`DefaultMCPToolHandler` so the LRU client cache, error
normalisation, and approval flow remain unchanged.
The ``tools/list`` path uses a transient :class:`MCPStreamableHTTPTool`
(``load_tools=False`` so MCP discovery only happens once via the
explicit ``session.list_tools()`` call). The same caller-supplied
``httpx.AsyncClient`` is reused so the bearer token and any other
transport-level configuration stay consistent with the cached calls.
"""
def __init__(self, inner: DefaultMCPToolHandler, http_client: httpx.AsyncClient) -> None:
self._inner = inner
self._http_client = http_client
async def invoke_tool(self, invocation: MCPToolInvocation) -> MCPToolResult:
if invocation.tool_name == LIST_TOOLS_TOOL_NAME:
return await self._list_tools(invocation)
return await self._inner.invoke_tool(invocation)
async def _list_tools(self, invocation: MCPToolInvocation) -> MCPToolResult:
if invocation.arguments:
return MCPToolResult(
outputs=[Content.from_text("Error: 'tools/list' does not accept arguments.")],
is_error=True,
error_message="'tools/list' does not accept arguments.",
)
# Snapshot headers so the closure does not see later mutations.
captured_headers = dict(invocation.headers)
def _header_provider(_kwargs: dict[str, Any]) -> dict[str, str]:
return dict(captured_headers)
tool = MCPStreamableHTTPTool(
name=invocation.server_label or "foundry_toolbox_list",
url=invocation.server_url,
http_client=self._http_client,
header_provider=_header_provider if captured_headers else None,
load_tools=False,
load_prompts=False,
)
try:
await tool.connect()
tool_list = await tool.session.list_tools() # type: ignore[union-attr]
payload = {
"tools": [
{
"name": entry.name,
"description": entry.description,
"inputSchema": entry.inputSchema,
"outputSchema": entry.outputSchema,
}
for entry in tool_list.tools
]
}
return MCPToolResult(outputs=[Content.from_text(json.dumps(payload))])
except Exception as exc: # noqa: BLE001 - surface as tool error per protocol contract
message = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__
return MCPToolResult(
outputs=[Content.from_text(f"Error: {message}")],
is_error=True,
error_message=message,
)
finally:
with contextlib.suppress(Exception):
await tool.close()
async def aclose(self) -> None:
await self._inner.aclose()
async def __aenter__(self) -> "_ToolboxMcpToolHandler":
return self
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
await self.aclose()
async def main() -> None:
"""Run the Foundry toolbox MCP workflow."""
# 1. Read configuration. ``FOUNDRY_PROJECT_ENDPOINT`` and
@@ -366,9 +183,7 @@ async def main() -> None:
toolbox_name = os.environ.get("FOUNDRY_TOOLBOX_NAME", DEFAULT_TOOLBOX_NAME)
toolbox_api_version = os.environ.get("FOUNDRY_TOOLBOX_API_VERSION", DEFAULT_TOOLBOX_API_VERSION)
docs_server_label = os.environ.get("FOUNDRY_TOOLBOX_DOCS_SERVER_LABEL", DEFAULT_DOCS_SERVER_LABEL)
web_search_tool_name = os.environ.get(
"FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME", DEFAULT_WEB_SEARCH_TOOL_NAME
)
web_search_tool_name = os.environ.get("FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME", DEFAULT_WEB_SEARCH_TOOL_NAME)
print("=" * 60)
print("Invoke Foundry Toolbox MCP Workflow Demo")
@@ -382,17 +197,20 @@ async def main() -> None:
project_endpoint=project_endpoint,
)
# 3. Resolve the toolbox MCP proxy URL and publish all dynamic values
# the YAML expects via ``Env.*``. Setting them after toolbox
# creation ensures the URL points at the freshly created version.
# 3. Resolve the toolbox MCP proxy URL. The workflow YAML references
# these values via ``=Env.FOUNDRY_TOOLBOX_*``; we publish them
# through ``WorkflowFactory(configuration=...)`` so the values stay scoped to
# this workflow.
toolbox_endpoint = os.environ.get("FOUNDRY_TOOLBOX_ENDPOINT") or build_toolbox_mcp_server_url(
project_endpoint=project_endpoint,
name=toolbox_name,
api_version=toolbox_api_version,
)
os.environ["FOUNDRY_TOOLBOX_MCP_SERVER_URL"] = toolbox_endpoint
os.environ["FOUNDRY_TOOLBOX_DOCS_SERVER_LABEL"] = docs_server_label
os.environ["FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME"] = web_search_tool_name
workflow_configuration: dict[str, str] = {
"FOUNDRY_TOOLBOX_MCP_SERVER_URL": toolbox_endpoint,
"FOUNDRY_TOOLBOX_DOCS_SERVER_LABEL": docs_server_label,
"FOUNDRY_TOOLBOX_WEB_SEARCH_TOOL_NAME": web_search_tool_name,
}
print(f"Toolbox endpoint: {toolbox_endpoint}")
print()
@@ -413,9 +231,9 @@ async def main() -> None:
# 5. Build a bearer-authenticated httpx client. The same client is
# reused for every MCP request: the LRU cache inside
# ``DefaultMCPToolHandler`` will keep a single MCP session alive
# for the toolbox URL, and the ``tools/list`` interceptor reuses
# the same httpx client so headers / auth stay consistent.
# ``DefaultMCPToolHandler`` keeps a single MCP session alive
# for the toolbox URL, and ``tools/list`` reuses that same
# cached session for full transport-level consistency.
#
# Key configuration choices:
# * ``headers=FOUNDRY_FEATURES_HEADERS`` attaches the
@@ -451,36 +269,32 @@ async def main() -> None:
# The Foundry AAD bearer token is scoped to ``https://ai.azure.com``
# but we still refuse to attach it to any URL we did not provision —
# if the YAML resolves a different ``serverUrl`` (e.g. via a tampered
# ``Env.*`` value or a config injection), returning ``None`` causes
# ``DefaultMCPToolHandler`` to fall back to an unauthenticated client,
# which will fail to authenticate to the proxy instead of forwarding
# the token outbound. Mirrors the .NET sample's
# ``httpClientProvider`` URL guard.
# ``Env.*`` value or a config injection), fail closed by raising so
# ``DefaultMCPToolHandler`` cannot fall back to an unauthenticated
# client that silently leaks the request shape.
if invocation.server_url.casefold() != toolbox_endpoint.casefold():
print(
f"[security] Refusing to attach Foundry bearer token to unexpected MCP URL: "
f"{invocation.server_url}",
file=sys.stderr,
raise ValueError(
f"Refusing to attach Foundry bearer token to unexpected MCP URL: "
f"{invocation.server_url!r}. Expected: {toolbox_endpoint!r}."
)
return None
return http_client
async with (
http_client,
DefaultMCPToolHandler(client_provider=_client_provider) as inner_handler,
_ToolboxMcpToolHandler(inner_handler, http_client) as mcp_handler,
DefaultMCPToolHandler(client_provider=_client_provider) as mcp_handler,
):
factory = WorkflowFactory(
agents={AGENT_NAME: summary_agent},
mcp_tool_handler=mcp_handler,
# The workflow YAML references ``=Env.FOUNDRY_TOOLBOX_*`` to keep
# the sample's toolbox URL / tool names configurable without
# editing the YAML. ``WorkflowFactory`` defaults to ``safe_mode=True``
# which would block those expressions; this sample opts in to the
# less-safe mode because we control both the YAML and the env
# vars. Do NOT copy this flag into a workflow that loads YAML
# from untrusted sources.
safe_mode=False,
# the toolbox URL / tool names configurable without editing the
# YAML. We supply those values through ``configuration`` so the
# PowerFx ``Env`` symbol is populated from a local dict instead
# of the process environment. ``restrict_env_to_configuration``
# defaults to ``True`` which suppresses any ``os.environ``
# fallback — the workflow only sees the keys explicitly listed
# in ``workflow_configuration`` below.
configuration=workflow_configuration,
)
workflow_path = Path(__file__).parent / "workflow.yaml"
@@ -0,0 +1,116 @@
# Copyright (c) Microsoft. All rights reserved.
"""Foundry toolbox provisioning helper for the ``invoke_foundry_toolbox_mcp`` sample.
This module is intentionally narrow: it covers the one-off **administrative**
setup needed to (re)create a Foundry toolbox so the sample can be run
end-to-end without manual portal/CLI steps. Workflow execution, MCP
handling, and agent orchestration live in :mod:`main`.
Toolboxes are normally provisioned through the Foundry portal or a separate
deployment script. Bundling the provisioning step here keeps the sample
self-contained and re-runnable.
The Foundry-Features preview header is exported here as well so the
runtime MCP client in ``main.py`` can attach it on every outbound request
(the MCP ``initialize`` handshake also requires the flag, not just the
toolbox administration calls).
"""
from collections.abc import Mapping
from azure.identity import AzureCliCredential
DEFAULT_DOCS_MCP_SERVER_URL = "https://learn.microsoft.com/api/mcp"
# Bump the ``az.cmd`` subprocess timeout from the default 10s. On Windows
# the Azure CLI batch wrapper can take noticeably longer than 10s to
# return a token (cold-start + ``az`` self-update checks + AAD round-trip),
# which surfaces as ``CredentialUnavailableError: Failed to invoke the
# Azure CLI`` after a ``subprocess.TimeoutExpired`` from the credential's
# internal call.
AZ_CLI_PROCESS_TIMEOUT_SECONDS = 60
# Toolbox administration AND runtime MCP traffic are both gated by an
# Azure AI Foundry preview feature flag. The .NET sample injects this
# header via a pipeline policy on the ``AgentAdministrationClient``;
# the Python ``AIProjectClient`` doesn't add it automatically, so we pass
# it as a per-call header on every toolbox admin operation (delete +
# create_version) here, and the runtime code in ``main.py`` attaches it
# as a default header on the ``httpx.AsyncClient`` so it travels on the
# MCP ``initialize`` handshake as well. Without this header on admin
# calls, provisioning succeeds at the HTTP layer but the toolbox is
# never wired up to the MCP endpoint — surfacing at runtime as "MCP
# server failed to initialize: Session terminated" on the first
# ``InvokeMcpTool`` call.
FOUNDRY_FEATURES_HEADER_NAME = "Foundry-Features"
FOUNDRY_FEATURES_HEADER_VALUE = "Toolboxes=V1Preview"
FOUNDRY_FEATURES_HEADERS: Mapping[str, str] = {
FOUNDRY_FEATURES_HEADER_NAME: FOUNDRY_FEATURES_HEADER_VALUE,
}
def build_toolbox_mcp_server_url(project_endpoint: str, name: str, api_version: str) -> str:
"""Compose the Foundry toolbox MCP proxy URL.
Toolboxes provisioned via ``AIProjectClient.beta.toolboxes`` live under
the ``/toolboxes/{name}`` resource path (the Python SDK's
``BetaToolboxesOperations`` routes POST/GET/DELETE there — see
``azure/ai/projects/operations/_operations.py``). Their MCP proxy URL
is ``<project_endpoint>/toolboxes/{name}/mcp?api-version=<api_version>``,
matching the .NET sample.
"""
base = project_endpoint.rstrip("/")
return f"{base}/toolboxes/{name}/mcp?api-version={api_version}"
def create_sample_toolbox(
*,
name: str,
docs_server_label: str,
project_endpoint: str,
docs_server_url: str = DEFAULT_DOCS_MCP_SERVER_URL,
) -> None:
"""Provision a toolbox version in the Foundry project (idempotent).
Deletes any existing toolbox under ``name`` and then creates a new
version that bundles:
- the Microsoft Learn Docs MCP server
(``server_label=docs_server_label``), and
- the Foundry built-in ``web_search`` tool.
Uses ``AzureCliCredential`` because the sample is meant to be run by
a developer with ``az login`` already configured; switch to a managed
identity / service principal credential for production deployments.
"""
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MCPTool, Tool, WebSearchTool
from azure.core.exceptions import ResourceNotFoundError
with (
AzureCliCredential(process_timeout=AZ_CLI_PROCESS_TIMEOUT_SECONDS) as credential,
AIProjectClient(credential=credential, endpoint=project_endpoint) as project_client,
):
try:
project_client.beta.toolboxes.delete(name, headers=FOUNDRY_FEATURES_HEADERS)
print(f"Toolbox '{name}' deleted (replacing with a fresh version).")
except ResourceNotFoundError:
pass
tools: list[Tool] = [
MCPTool(
server_label=docs_server_label,
server_url=docs_server_url,
require_approval="never",
),
WebSearchTool(),
]
created = project_client.beta.toolboxes.create_version(
name=name,
description="Sample toolbox combining Microsoft Learn Docs MCP and Foundry web search.",
tools=tools,
headers=FOUNDRY_FEATURES_HEADERS,
)
print(f"Created toolbox {created.name}@{created.version} ({len(created.tools)} tool(s)).")
@@ -7,10 +7,9 @@
# The workflow:
# 1. Accepts a documentation / web search query as input.
# 2. Lists the tools exposed by the toolbox using the reserved
# toolName: ``tools/list``. The Python ``DefaultMCPToolHandler``
# does not intercept this name on its own; the sample's host code
# wraps it with a small handler that translates ``tools/list`` to
# an MCP ``session.list_tools()`` call.
# toolName: ``tools/list``. ``DefaultMCPToolHandler`` intercepts
# this reserved name natively and translates it
# to an MCP ``session.list_tools()`` call, returning a JSON catalog.
# 3. Invokes the Microsoft Learn ``microsoft_docs_search`` MCP tool
# surfaced by the toolbox. Tool names from MCP-server-backed
# toolbox tools are namespaced as ``<server_label>___<tool_name>``.
@@ -41,9 +40,7 @@ trigger:
variable: Local.SearchQuery
value: =Workflow.Inputs.text
# List the tools exposed by the toolbox MCP proxy. The sample's
# custom MCPToolHandler intercepts the reserved ``tools/list`` name
# and returns the toolbox tool list as JSON.
# List the tools exposed by the toolbox MCP proxy.
#
# We intentionally OMIT ``conversationId`` here: the tool list is
# metadata for the demo, not useful context for the downstream