Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion python/packages/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,13 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID
emits a `FutureWarning` because that fallback may change in a future release. A name list given as a bare string is one
name, not a substring pattern. `default` is local-only: hosted MCP helpers (`get_mcp_tool`) do not read it. Tools and
prompts discovered later (for example after `tools/list_changed`) use the policy at discovery time; retained
functions keep their resolved mode.
functions keep their resolved mode under static policies. Alternatively, pass a synchronous callable receiving
the discovered `mcp.types.Tool` or `mcp.types.Prompt` and returning `"always_require"` or `"never_require"`
for every item, including its default decision. Callback results of `None` are invalid; constructor-level
`None` keeps its default behavior. Callable policies run on each discovery refresh for new and retained functions;
results are validated and staged across all pages before publication. Exceptions preserve the previous
snapshot. `FoundryToolbox` supplies its metadata parser as this callable when no explicit caller policy is
configured; ordinary MCP servers do not interpret Foundry metadata.
- **Progressive MCP disclosure** (`use_progressive_disclosure`, `always_load`) - When enabled on any `MCPTool` subclass, the initial model-facing surface is loader tools (`list_mcp_tools` / `load_tool` / `unload_tool`, prefixed by `tool_name_prefix` when configured) plus allowed tools selected by `always_load` and tools loaded earlier on the same `MCPTool` instance. `list_mcp_tools` only reports tools that pass `allowed_tools`; filtered tools are not listed or loadable. Loader tool names are reserved in progressive mode: remote MCP tools whose local generated name collides with a loader name are omitted from the initial/listed surface, and explicit `load_tool` calls return a model-visible message pointing callers to `tool_name_prefix` or excluding the colliding tool. `load_tool` accepts one tool name or a list of tool names and uses `FunctionInvocationContext.add_tools(...)` so the selected generated MCP `FunctionTool`s become available on the next function-calling iteration while keeping existing approval mode, argument filtering, header-provider runtime kwargs, result parsing, and OTel. `unload_tool` accepts one dynamically loaded tool name or a list of names and removes them from the live tool list and persisted progressive surface, but it does not remove tools configured in `always_load`. Invalid `always_load` entries are ignored like unmatched `allowed_tools` entries.
- **Tool discovery refresh** - Validate the complete current tool snapshot alongside retained non-tool functions,
not stale tool wrappers. Successful refreshes atomically replace the previous tool set and metadata, including
Expand Down
98 changes: 87 additions & 11 deletions python/packages/core/agent_framework/_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,7 +1163,12 @@ def __init__(
self,
name: str,
description: str | None = None,
approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None,
approval_mode: (
Literal["always_require", "never_require"]
| MCPSpecificApproval
| Callable[[types.Tool | types.Prompt], Literal["always_require", "never_require"]]
Comment thread
eavanvalkenburg marked this conversation as resolved.
Resolved
| None
) = None,
allowed_tools: Collection[str] | None = None,
tool_name_prefix: str | None = None,
load_tools: bool = True,
Expand Down Expand Up @@ -1228,7 +1233,7 @@ def __init__(
raise ValueError(
f"tool_result_content must be one of {sorted(allowed_modes)}, got {tool_result_content!r}."
)
if isinstance(approval_mode, dict):
if not callable(approval_mode) and isinstance(approval_mode, dict):
_mcp_approval_default(approval_mode, warn_stacklevel=_mcp_constructor_stacklevel(self))
self.name = name
self.description = description or ""
Expand Down Expand Up @@ -1677,7 +1682,7 @@ def _filtered_functions(self) -> list[FunctionTool]:
def _validate_config_names(self, functions: Sequence[FunctionTool]) -> None:
"""Reject configured names that identify more than one raw remote name."""
configured_names = set(self.allowed_tools or ())
if isinstance(self.approval_mode, dict):
if not callable(self.approval_mode) and isinstance(self.approval_mode, dict):
configured_names.update(_mcp_approval_names(self.approval_mode.get("always_require_approval")))
configured_names.update(_mcp_approval_names(self.approval_mode.get("never_require_approval")))
if not configured_names:
Expand Down Expand Up @@ -2571,6 +2576,10 @@ async def _connect_on_owner(
elif connection.client is None:
raise RuntimeError("MCP connection has neither a Client nor a ClientSession.")
functions_before_discovery = self._functions.copy()
approval_modes_before_discovery = [
Comment thread
eavanvalkenburg marked this conversation as resolved.
Resolved
(function, function.approval_mode) for function in functions_before_discovery
]
progressive_loaded_names_before_discovery = self._progressive_loaded_tool_names.copy()
call_meta_before_discovery = self._tool_call_meta_by_name
param_names_before_discovery = self._tool_param_names_by_name
annotations_before_discovery = self._tool_annotations_by_name
Expand Down Expand Up @@ -2606,10 +2615,14 @@ async def _connect_on_owner(
try:
await self._close_on_owner()
finally:
for function, approval_mode in approval_modes_before_discovery:
function.approval_mode = approval_mode
self._functions[:] = functions_before_discovery
self._tool_call_meta_by_name = call_meta_before_discovery
self._tool_param_names_by_name = param_names_before_discovery
self._tool_annotations_by_name = annotations_before_discovery
self._progressive_loaded_tool_names.clear()
self._progressive_loaded_tool_names.update(progressive_loaded_names_before_discovery)
raise

async def _prepare_for_run(self, kwargs: Mapping[str, Any]) -> None:
Expand Down Expand Up @@ -2948,8 +2961,23 @@ async def _safe_reload() -> None:
def _determine_approval_mode(
self,
*candidate_names: str,
item: types.Tool | types.Prompt | None = None,
is_retained: bool = False,
) -> Literal["always_require", "never_require"] | None:
"""Resolve discovery policy, preserving retained functions under static policies."""
approval_mode = self.approval_mode
if callable(approval_mode):
if item is None:
raise ValueError("A discovered MCP tool or prompt is required for callable approval_mode.")
resolved_mode = approval_mode(item)
if resolved_mode not in _MCP_APPROVAL_MODES:
raise ToolExecutionException(
f"approval_mode callable for MCP item {item.name!r} must return "
"'always_require' or 'never_require', including its default decision."
)
return resolved_mode
if is_retained:
return None
if not isinstance(approval_mode, dict):
return approval_mode # type: ignore[return-value]
always_require = _mcp_approval_names(approval_mode.get("always_require_approval"))
Expand Down Expand Up @@ -3003,6 +3031,7 @@ async def _load_prompts_locked(self) -> None:
prompt_functions: list[FunctionTool] = []
retained_prompt_names: set[str] = set()
new_functions: list[FunctionTool] = []
prompt_approval_updates: dict[str, Literal["always_require", "never_require"]] = {}
items_loaded = 0

def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None:
Expand All @@ -3029,7 +3058,8 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None:
local_name=local_name,
normalized_name=normalized_name,
remote_name=prompt.name,
)
),
item=prompt,
)
func: FunctionTool = FunctionTool(
func=_make_mcp_prompt_caller(self, prompt.name),
Expand All @@ -3055,6 +3085,8 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None:
and existing_prompt.parameters() == func.parameters()
):
# Keep the unchanged prompt function so local customizations survive a refresh.
if callable(self.approval_mode) and approval_mode is not None:
prompt_approval_updates[local_name] = approval_mode
prompt_functions.append(existing_prompt)
continue
prompt_functions.append(func)
Expand Down Expand Up @@ -3096,6 +3128,9 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None:
if self._function_load_callback is not None:
for function in new_functions:
self._function_load_callback(function, None)
for function in prompt_functions:
if function.name in prompt_approval_updates:
function.approval_mode = prompt_approval_updates[function.name]
self._functions[:] = current_functions
# Only prompts that keep the same remote identity retain their progressive-load state; a
# different remote prompt that normalizes to the same local name must start unloaded.
Expand Down Expand Up @@ -3209,6 +3244,7 @@ async def _load_tools_locked(self) -> None:
tool_call_meta_by_name: dict[str, dict[str, Any]] = {}
tool_param_names_by_name: dict[str, set[str]] = {}
tool_annotations_by_name: dict[str, Any] = {}
tool_approval_updates: dict[str, Literal["always_require", "never_require"]] = {}
items_loaded = 0

def stage_tool_page(tool_list: types.ListToolsResult) -> None:
Expand Down Expand Up @@ -3270,19 +3306,26 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None:
existing_tool = existing_tools.get(local_name)
if (
existing_tool is not None
and (existing_tool.additional_properties or {}).get(_MCP_REMOTE_NAME_KEY) == tool.name
and (existing_tool.additional_properties or {}).get(_MCP_REMOTE_NAME_KEY) != tool.name
):
reused_tool_names.add(local_name)
continue
existing_tool = None

approval_mode = self._determine_approval_mode(
*_mcp_config_candidate_names(
local_name=local_name,
normalized_name=normalized_name,
remote_name=tool.name,
)
),
item=tool,
is_retained=existing_tool is not None,
)

if existing_tool is not None:
reused_tool_names.add(local_name)
if approval_mode is not None:
tool_approval_updates[local_name] = approval_mode
continue

# Create FunctionTools out of each tool
func: FunctionTool = FunctionTool(
func=_make_mcp_tool_caller(self, tool.name),
Expand Down Expand Up @@ -3346,6 +3389,9 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None:
and self._function_load_callback is not None
):
self._function_load_callback(function, tool_annotations_by_name[remote_name])
for function in current_functions:
if function.name in tool_approval_updates:
function.approval_mode = tool_approval_updates[function.name]
Comment thread
eavanvalkenburg marked this conversation as resolved.
Resolved
Comment thread
eavanvalkenburg marked this conversation as resolved.
Resolved
self._functions[:] = current_functions
self._tool_call_meta_by_name = tool_call_meta_by_name
self._tool_param_names_by_name = tool_param_names_by_name
Expand Down Expand Up @@ -3808,7 +3854,12 @@ def __init__(
mcp_client: Client | None = None,
session: ClientSession | None = None,
description: str | None = None,
approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None,
approval_mode: (
Literal["always_require", "never_require"]
| MCPSpecificApproval
| Callable[[types.Tool | types.Prompt], Literal["always_require", "never_require"]]
| None
) = None,
allowed_tools: Collection[str] | None = None,
use_progressive_disclosure: bool = False,
always_load: Collection[str] | None = None,
Expand Down Expand Up @@ -3880,6 +3931,11 @@ def __init__(
"never_require") for tools and prompts named in neither list. Without `default`, those tools
and prompts do not require approval, and setting `never_require_approval` without `default`
emits a ``FutureWarning``.
- A synchronous callable receiving the discovered ``mcp.types.Tool`` or ``mcp.types.Prompt``
and returning "always_require" or "never_require", including its default decision. It runs once
per item on each discovery refresh, including retained functions, before publication.
Invalid results raise ``ToolExecutionException``; callback exceptions propagate.
Callbacks should not mutate the discovery item or perform side effects.
A tool listed in both lists requires approval. ``None`` (the default) does not require approval.
allowed_tools: Optional allow-list of MCP tool names to expose as functions.
``None`` (the default) exposes every tool advertised by the MCP server.
Expand Down Expand Up @@ -4079,7 +4135,12 @@ def __init__(
mcp_client: Client | None = None,
session: ClientSession | None = None,
description: str | None = None,
approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None,
approval_mode: (
Literal["always_require", "never_require"]
| MCPSpecificApproval
| Callable[[types.Tool | types.Prompt], Literal["always_require", "never_require"]]
| None
) = None,
allowed_tools: Collection[str] | None = None,
use_progressive_disclosure: bool = False,
always_load: Collection[str] | None = None,
Expand Down Expand Up @@ -4154,6 +4215,11 @@ def __init__(
"never_require") for tools and prompts named in neither list. Without `default`, those tools
and prompts do not require approval, and setting `never_require_approval` without `default`
emits a ``FutureWarning``.
- A synchronous callable receiving the discovered ``mcp.types.Tool`` or ``mcp.types.Prompt``
and returning "always_require" or "never_require", including its default decision. It runs once
per item on each discovery refresh, including retained functions, before publication.
Invalid results raise ``ToolExecutionException``; callback exceptions propagate.
Callbacks should not mutate the discovery item or perform side effects.
A tool listed in both lists requires approval. ``None`` (the default) does not require approval.
allowed_tools: Optional allow-list of MCP tool names to expose as functions.
``None`` (the default) exposes every tool advertised by the MCP server.
Expand Down Expand Up @@ -4762,7 +4828,12 @@ def __init__(
request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS,
session: ClientSession | None = None,
description: str | None = None,
approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None,
approval_mode: (
Literal["always_require", "never_require"]
| MCPSpecificApproval
| Callable[[types.Tool | types.Prompt], Literal["always_require", "never_require"]]
| None
) = None,
allowed_tools: Collection[str] | None = None,
use_progressive_disclosure: bool = False,
always_load: Collection[str] | None = None,
Expand Down Expand Up @@ -4819,6 +4890,11 @@ def __init__(
"never_require") for tools and prompts named in neither list. Without `default`, those tools
and prompts do not require approval, and setting `never_require_approval` without `default`
emits a ``FutureWarning``.
- A synchronous callable receiving the discovered ``mcp.types.Tool`` or ``mcp.types.Prompt``
and returning "always_require" or "never_require", including its default decision. It runs once
per item on each discovery refresh, including retained functions, before publication.
Invalid results raise ``ToolExecutionException``; callback exceptions propagate.
Callbacks should not mutate the discovery item or perform side effects.
A tool listed in both lists requires approval. ``None`` (the default) does not require approval.
allowed_tools: Optional allow-list of MCP tool names to expose as functions.
``None`` (the default) exposes every tool advertised by the MCP server.
Expand Down
23 changes: 23 additions & 0 deletions python/packages/foundry_hosting/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@

This package provides the integration of Agent Framework agents and workflows with the Foundry Agent Server, which can be hosted on Foundry infrastructure.

## Toolbox tool approvals

`FoundryToolbox` uses each discovered tool's `_meta.tool_configuration.require_approval` when
`approval_mode` is omitted or `None`. See the
[Foundry approval configuration](https://learn.microsoft.com/python/api/azure-ai-projects/azure.ai.projects.models.mcptoolrequireapproval)
for supported metadata shapes.

Unlike regular MCP tools, Toolbox `approval_mode=None` does not mean no approval.
Use `"never_require"` to disable local approval or `"always_require"` to require it for every function.
Any explicit non-`None` policy, including a dictionary or callable, replaces metadata handling entirely.
Missing metadata defaults to no approval; malformed metadata raises `ToolExecutionException`.

Metadata filters use remote/original tool names, not local prefixes. Filter criteria must all match;
`always` wins overlaps and unmatched filter-policy tools require approval. Discovery refreshes and reconnects
reapply the policy; failed refreshes preserve the previous complete snapshot and approval modes.

**Trust boundary:** This Foundry-specific integration trusts the supplied `annotations.readOnlyHint`
when evaluating `read_only` filters, including rules that skip approval. It does not independently
verify that classification or enforce read-only behavior. Applications must trust the classifications
supplied through their configured Toolbox. The private metadata parser is intended only for Foundry
Toolbox; reusing it elsewhere provides no security or compatibility guarantees. It is not a
general-purpose MCP approval policy.

## Agent instances and factories

`ResponsesHostServer` and `InvocationsHostServer` accept an agent instance or a zero-argument callable through the
Expand Down
Loading
Loading