Imported from microsoft/agent-framework (
python/packages/core/AGENTS.md). Install upstream withnpx skills add microsoft/agent-framework --skill core. Copyright stays with the author.
Core Package (agent-framework-core)
The foundation package containing all core abstractions, types, and built-in OpenAI/Azure OpenAI support.
Module Structure
agent_framework/
├── __init__.py # Lazy runtime public API exports
├── __init__.pyi # Public API typing surface for lazy root exports
├── security.py # Public security primitives, middleware, and tools
├── _agents.py # Agent implementations
├── _clients.py # Chat client base classes and protocols
├── _types.py # Core types (Message, ChatResponse, Content, etc.)
├── _tools.py # Tool definitions and function invocation
├── _vectors.py # Vector store models, CRUD/search abstractions, and protocols
├── _middleware.py # Middleware system for request/response interception
├── _sessions.py # AgentSession and context provider abstractions
├── _filesystem.py # Private filesystem safety helpers (atomic writes, link detection, storage-key derivation)
├── _skills.py # Agent Skills system (models, executors, provider)
├── _mcp.py # Model Context Protocol support
├── _telemetry.py # User-Agent identity and internal feature-usage mask
├── _workflows/ # Workflow orchestration (sequential, concurrent, handoff, etc.)
├── openai/ # Built-in OpenAI client
├── azure/ # Lazy-loading entry point for Azure integrations
└── <provider>/ # Other lazy-loading provider folders
Core Classes
Root Public API (__init__.py / __init__.pyi)
agent_framework.__init__uses lazy module-level__getattr__for most public exports to keep coldimport agent_frameworklightweight.- Keep
_LAZY_MODULE_EXPORTS,_LAZY_EXPORTS, the explicit runtime__all__, and__init__.pyisynchronized whenever adding, removing, or moving a root public export. - Runtime
__all__is still required forfrom agent_framework import *; the.pyifile is for type checkers and editors and does not replace runtime exports. - Public deprecation behavior for a lazy export belongs in the owning module. The root package should delegate via the normal lazy export map instead of carrying one-off branches.
Settings (_settings.py)
SecretStringis a non-strwrapper: string conversion, representation, formatting, and concatenation display a mask. String-only APIs such asstr.join()and JSON encoding reject it unless callers explicitly convert it. Useget_secret_value()when passing credentials to provider SDKs;str(secret)returns the mask.load_settingsaccepts plain string overrides forSecretStringfields and wraps them, as it does for environment and.envvalues. ExistingSecretStringoverrides are preserved. Invalid supplied numeric and boolean environment or.envvalues raiseValueErroridentifying the field and source instead of falling back to raw strings.
Agents (_agents.py)
SupportsAgentRun- Protocol defining the agent interfaceBaseAgent- Abstract base class for agentsAgent- Main agent class wrapping a chat client with tools, instructions, and middlewareRawAgent.open()/close()(inherited byAgent) - Explicitly enter the client's and configured MCP tools' async contexts, then release them along with lazily connected MCP tools.async with agentdelegates to these methods; a partially failedopen()closes resources already entered.- Providers that store service-owned continuation handles in
AgentSession.statedeclare their keys throughservice_session_state_keys.as_tool(propagate_session=True)combines declarations from the parent and child agents and their clients to isolate those handles in both directions while ordinary application-owned state propagates. The automatic function loop places parent declarations onFunctionInvocationContext; direct or custom-loop invocation must setparent_service_session_state_keysexplicitly for a non-empty shared session and otherwise fails closed.
Chat Clients (_clients.py)
SupportsChatGetResponse- Protocol for chat client implementationsBaseChatClient- Abstract base class with middleware support; subclasses implement_inner_get_response()and_inner_get_streaming_response()
Types (_types.py)
Message- Represents a chat message with role, content, and metadataChatResponse- Response from a chat client containing messages and usageChatResponseUpdate- Streaming response updateAgentResponse/AgentResponseUpdate- Agent-level response wrappersContent- Base class for message content (text, function calls, images, etc.)- Content identity and metadata -
function_call.idis Agent Framework occurrence identity; provider item IDs belong in the provider namespace.function_call.hostedcontrols execution ownership, whileserver_nameis the descriptive hosted-server boundary and never implieshosted=True. Provider metadata uses one-leveladditional_propertiesnamespaces and streamed mergeable content usesmerge_mode; response updates can use the same field to replace all contents of one logical message; see spec 005. - Computer use -
ComputerSafetyCheckand theContent.from_computer_tool_call/from_computer_tool_resultconstructors are experimental underCOMPUTER_USE; the rest ofContentretains its existing stage. Computer results can omit screenshots in core; OpenAI-based connectors require them when converting to Responses items. Completed call/result pairs remain in the transcript but are not user-input requests. ChatOptions- TypedDict for chat request options
Tools (_tools.py)
ToolProtocol- Protocol for tool definitionsFunctionTool- Wraps Python functions as tools with JSON schema generation@tooldecorator - Converts functions to toolsuse_function_invocation()- Decorator to add automatic function calling to chat clients_normalize_tool_description_format/_format_tool_parameters- Private configuration normalizer and structured parameter formatter shared by Hyperlight and Monty descriptions. They validate and detach compact/JSON settings, return detached parameter data, and fall back to full JSON Schema when compact data cannot preserve constraints. They do not changeFunctionTool.parameters()or render runtime-specific text.
Vector stores
The vector store API is experimental under the shared VECTOR_STORES feature ID.
@vectorstoremodel- Declares key, data, and vector fields on dataclasses, Pydantic models, and plain classesregister_vectorstoremodel- Registers one definition and msgspec-backed codec pair per model typeVectorStoreField- Frozen core key/data/vector metadata; common index and distance values remain open to provider-defined strings, key fields can be store-generated, and copiedprovider_annotationsremains mutable for connector-specific configurationFilter/FilterGroup- Mutable data-only filter inputs shared by local and remote vector stores; collection operations bound structural traversal before copying and pass an independent snapshot to connectors. Parameter detection includes collection members and mapping keys; string operators require string operands after resolutionParam- Native typed search-tool parameter reference embedded in filter values or paging options- Defaults and supplied mutable values are copied per filter invocation, including for definition-less search tools
- Filter parameters may opt into null omission with a nullable type and explicit
default=None, such asParam("text", str | None, default=None, omit_if_none=True); absent/null arguments remove that leaf, while remaining AND/OR children still apply. Empty groups (including NOT with an omitted child) are removed recursively; removing the whole tree means no filter. Paging parameters do not support null omission.
BaseVectorCollection- Base class for collection lifecycle and msgspec-backed record CRUD operations; upserts generate embeddings by default, retrieval excludes vectors by default, and filtered retrieval is an alternate mode to key lookup. Agent-facing CRUD tools use itskey_json_schema,key_from_json, andkey_to_jsonhooks so connectors can preserve native key identity at JSON boundaries.- Embedding generation selection -
generate_vectors=Trueregenerates every vector field,Falsepreserves all values, and a list or tuple of logical vector field names generates only those fields so connectors can combine local, precomputed, and provider-side vectorization - Vector payloads - Shared dense query/generated vectors accept numeric sequences and binary bytes; connectors
declare supported element/representation types. Sparse vectors remain provider-native through codecs or
search(values=...), not a core sparse type. - Vector dimensions - Final dense sequence lengths are checked after optional generation for the whole write batch before connector conversion or writes, and for the selected query field before search dispatch. In-memory queries also check their normalized numeric sequence, including array-like inputs and empty collections. These are length checks, not element validation; null vectors, source text, binary payloads, and non-sequence provider-native representations remain connector-owned.
BaseVectorStore- Base class for stores that create collection clientsBaseVectorSearch- Base class for vector and keyword-hybrid search; core validates portable requests and deserializes results without interpreting thresholds or re-filtering returned scores. Connectors own scoring, filter execution, score thresholds (including provider-defined/default metrics), and paging. Use native backend execution where available, otherwise an explicit connector-local fallback or reject unsupported options- Embedding request options -
upsertaccepts either flatembeddings_optionsfor all generated vector fields orembeddings_options_by_fieldkeyed by logical field name, never both.searchandcreate_vector_search_toolaccept flatembeddings_optionsfor local query generation. Core supplies declared field dimensions and rejects conflicting values before embedding; search ignores these options when a precomputed vector is supplied.create_upsert_toolandVectorCollectionContextProviderforward the same operation-specific settings to their generated tools. create_vector_search_tool- Creates an agent tool from anySupportsVectorSearchimplementationcreate_upsert_tool/create_get_tool/create_delete_tool- Create agent tools for collection CRUD; upsert and delete require approval by default, while get does not. Auto-generated keys are omitted from upsert input only when the record is a dictionary or the typed model declares a key default. Connector partial-write errors propagate because the collection contract cannot report unknown committed subsets.VectorStoreHistoryProvider- Stores full scoped conversation history in a provider-owned collection; optional embeddings enable session-scoped history search and optional compaction affects only loaded context. Embedding-enabled history requires an explicit collection name; physical retention, large-history paging, and concurrent clear semantics remain backing-store guarantees.VectorCollectionContextProvider- Adds instructions and configurable CRUD/search tools for a caller-owned collection. Callers explicitly provide a best-effort logical scope filter (orNone); it is not a security boundary. Independently configured additional search tools retain their own filters.InMemoryCollection/InMemoryStore- Dependency-free, process-local development and test implementation; cosine scoring scales finite inputs, all metrics reject non-finite scores, and unsupported distance functions fail before record scanning. Hamming scores/thresholds use the fraction of unequal dimensions, not a count. Scoring, filtering, and thresholds run locally before paging;DEFAULTmeans cosine distance and uses a maximum distance threshold. Shared serialization normalizes stored data; codecs and connector overrides remain trusted Python codeSupportsVectorUpsert/SupportsVectorSearch- Structural protocols for vector store capabilities
Middleware (_middleware.py)
AgentMiddleware- Intercepts agentrun()callsChatMiddleware- Intercepts chat clientget_response()callsFunctionMiddleware- Intercepts function/tool invocationsAgentContext/ChatContext/FunctionInvocationContext- Context objects passed through middleware. A tool can declare aFunctionInvocationContextparameter to receive it;context.toolsis the live, mutable tools list for the run, andcontext.add_tools(...)/context.remove_tools(...)enable progressive tool exposure (changes apply on the next function-calling iteration). Chat middleware that constructs provider-local replacement messages must callcontext.record_message_replacement(...)for every replacement before downstream compaction so complete summaries can reconcile to caller-owned messages without persisting the replacements themselves.MessageInjectionMiddleware- Session-scoped chat middleware that lets tools or other code enqueue messages for the next model call in the currentAgentSession; it drains queued messages into the next call and loops only when no function calls need to be handled by the function invocation layer.
Sessions (_sessions.py)
AgentSession- Manages conversation state and session metadataSessionStore- Experimental in-memory opaquesession_id -> AgentSessionsnapshot store; reads return independent copiesFileSessionStore- Experimental msgspec file-backed session snapshot store with atomic last-writer-wins updates; JSON is the default,serialization_format="msgpack"enables binary MessagePack, opaque keys are encoded to portable filenames, and only syntactically malformed snapshots are quarantined (schema, version, and state-decoder failures preserve the original file)- Storage-key derivation (
_filesystem._storage_key_segment) - Every component that maps a caller-controlled identifier (session id, owner id, memory scope) onto a storage location uses this one private helper:FileSessionStore/FileHistoryProvider(~session-),TodoFileStore(~todo-),MemoryFileStore(~memory-), andFileMemoryProvider(~scope-). Its contract is injectivity — two byte-distinct identifiers must not produce the same segment, because the segment is an isolation boundary. Identifiers that are already a safe single segment (lowercase ASCII alnum plus._-, no leading., no trailing./space, not a Windows reserved stem) are used verbatim so on-disk layouts stay readable; everything else is encoded as lowercase base32 under the component prefix, with asha256-digest segment past a length cap (_MAX_ENCODED_STORAGE_KEY_SEGMENT_LENGTH). Only that digest branch weakens the contract to collision resistance. The charset is deliberately narrow so the filesystem cannot fold two distinct segments together: non-ASCII values are encoded because macOS APFS/HFS+ fold NFC vs NFD, and uppercase values are encoded (never lowercased, which would collide with a genuine lowercase identifier) because NTFS and APFS are case-insensitive by default — base32'sa-z2-7alphabet is itself case-stable. Never pass such an identifier through a path normalizer (e.g._normalize_relative_path) to derive storage: that mapping is lossy, andid/id//id\would collide. New components must reuse this helper with their own~-prefixed namespace. register_state_type- Registers customAgentSession.stateclasses with stable, process-wide type IDs and optional mapping codecs. Provider modules own registration for their custom state types and should use package-qualified IDs. Implicit Pydantic registration remains temporarily withDeprecationWarning, but module-level registration is needed to guarantee cold-start restoration.ServiceSessionId- Mapping alias for structured service-owned continuation handles used inAgentSession.service_session_idSessionContext- Context object for session-scoped data during agent runs.extend_messages(...)can attach ordered, deduplicatedorigin_session_idsattribution when a provider injects content from other sessions.ContextProvider- Base class for context providers (RAG, memory systems)HistoryProvider- Base class for conversation history storageInMemoryHistoryProvider- Built-in session-state history provider for local runsFileHistoryProvider- Experimental append-only file-backed history provider; msgspec JSON Lines is the default andserialization_format="msgpack"uses length-prefixed binary MessagePack records. Customdumps/loadsremain as deprecated JSON-only compatibility hooks and emitDeprecationWarningwhen supplied.- Mixed computer/function workflow history - The default
HistoryProvider.after_rundefers completed local function results for loadable providers that store inputs until the computer reply arrives, so history records them once in call order. Customafter_runimplementations must handle this themselves.
Skills (_skills.py)
-
Skill frontmatter parsing - Local and MCP archive skill loaders use PyYAML's
SafeLoadernode composition, not dictionary construction, so duplicate mapping entries remain available for validation and no YAML object constructors run. Recognized root names must be lowercase and unique after YAML decoding. Scalar fields remain text (including numeric/boolean scalar spellings); null root values remain unset. Decoded keys and retained scalar values cannot contain Unicode surrogate code points, which cannot be encoded as UTF-8. Invalid optional metadata mappings or entries warn and are skipped; case-sensitive duplicate metadata keys keep the first valid value. Invalid YAML syntax or invalid recognized root fields reject the skill. Quoting, escapes, multiline folding/chomping, and line-ending normalization follow PyYAML. YAML merge keys (<<) are not expanded: they are invalid at the root and skipped with warnings in metadata. -
Skill- Abstract base for a skill definition bundling instructions (content) with frontmatter metadata, resources, and scripts. Concrete subclasses (InlineSkill,FileSkill,ClassSkill) accept afrontmatter=SkillFrontmatter(...)argument carrying the spec fields. Adding new spec fields is done in one place — onSkillFrontmatter— keeping the subclass constructors stable. -
SkillFrontmatter- L1 discovery metadata for a skill (name,description,license,compatibility,allowed_tools,metadata). All fields are mutable plain attributes; the constructor validatesname,description, andcompatibilityagainst the spec but post-construction assignments are not re-validated. Spec fields are reachable on every skill viaskill.frontmatter. -
SkillResource- Named supplementary content attached to a skill; holds either staticcontentor a dynamicfunction(sync or async). Exactly one must be provided. -
SkillScript- An executable script attached to a skill; inline scripts run in-process, while file-based scripts are delegated to a runner. Inline callbacks can declare aFunctionInvocationContextparameter (hidden from the schema) to access host values separately throughctx.kwargs. Customrun()overrides opt in with the same annotation; unannotated overrides retain runtime keyword forwarding. -
SkillScriptRunner- Protocol for file-based script execution. Any callable matching(skill, script, args) -> Anysatisfies it. Code-defined scripts do not use a runner. Runners can opt into context injection with an additional keyword-bindableFunctionInvocationContextparameter that has a default value. -
SkillScriptArgumentParser- Public type alias for an optional callable(raw args: dict | list[str] | str | None) -> dict | Nonethat converts the rawargsvalue before anInlineSkillScriptruns (applied before the inline list-args guard). It is an opt-in customization hook (port of .NET PR #6498) that lets callers support backends sending tool-call arguments in a non-conforming shape (e.g. vLLM JSON strings). The output is constrained to adict(named keyword arguments) orNone, because inline scripts bind arguments by keyword name. Supply it via theargument_parser=constructor arg onInlineSkillScript,InlineSkill(default for scripts added via@skill.script), orClassSkill(default for scripts discovered via@ClassSkill.script). WhenNone(the default), the raw value is used unchanged. File-based scripts are unaffected (their runner owns arg handling). -
SkillsProvider- Context provider (extendsContextProvider) that discovers file-based skills fromSKILL.mdfiles and/or accepts code-definedSkillinstances. Follows progressive disclosure: advertise → load → read resources / run scripts. By default all three tools it exposes (load_skill,read_skill_resource,run_skill_script) are registered withapproval_mode="always_require", so every skill operation needs approval. To run unattended, pass one of the static auto-approval rules toToolApprovalMiddleware(viaauto_approval_rules):SkillsProvider.read_only_tools_auto_approval_ruleapproves only the read-only tools (load_skill,read_skill_resource) while still prompting forrun_skill_script, andSkillsProvider.all_tools_auto_approval_ruleapproves every skill tool including script execution. Both rules reject any call carrying aserver_labelso they stay scoped to this provider's local tools and never auto-approve a same-named hosted tool. Alternatively, for trusted skills, the constructor /from_pathskwargsdisable_load_skill_approval,disable_read_skill_resource_approval, anddisable_run_skill_script_approval(all defaultFalse) opt individual tools out of approval entirely by registering them withapproval_mode="never_require"(the auto-approval rules only apply to tools that still require approval). The tool names are also exposed as class constants (LOAD_SKILL_TOOL_NAME,READ_SKILL_RESOURCE_TOOL_NAME,RUN_SKILL_SCRIPT_TOOL_NAME). -
FileSkillsSource-SkillsSourcethat discovers file-based skills by scanning configured root paths forSKILL.md. The configured root paths define the trust boundary and are used as given (a root may itself be a symlink); everything discovered below a root is link-checked and fails closed._discover_skill_directoriesrejects any entry that is a symbolic link, junction, or other reparse point (via the sharedagent_framework._filesystem.is_link_or_reparse_pointhelper) before descending into it, and rejects a directory whoseSKILL.mdis itself such a link — otherwise a link planted under a root would be adopted as the skill root, and since every later guard treats the skill root as the boundary and only inspects segments below it, the link itself would never be inspected. Resource and script discovery apply the same rule per path segment via_has_link_or_reparse_point_in_path; source-discovered resources and scripts retain a_SkillPathScopepairing their configured root with their skill directory, and repeat containment, regular-file, and link checks immediately before reading or execution — scanning every segment from the configured root down to the file, so a skill directory (or any directory between it and the root) swapped for a link after discovery is rejected too. AnOSErrorwhile inspecting an entry is treated as unsafe (skip / reject), never as "safe". -
MCPSkillsSource-SkillsSourcethat discovers Agent Skills served over MCP by reading the well-knownskill://index.json(SEP-2640). Index entries are dispatched by theirtype(case-insensitive):skill-mdentries become oneMCPSkilleach (itsSKILL.mdbody and sibling resources are fetched on demand viaresources/read), andarchiveentries are downloaded as a single ZIP blob and unpacked entirely in memory (via the private_ArchiveEntryLoader) into aFileSkillwhoseSKILL.mdbody drives it and whose sibling files (matching the resource extensions, within the search depth) become in-memoryInlineSkillResourceresources. Nothing is written to disk — there are no temporary directories to create, own, or prune (this is a deliberate divergence from .NET, which extracts ZIP archives to disk; it removes the temp-dir leak and the dangerous prune-of-unowned-subdirs footgun). Entries whose type has no handler (e.g.mcp-resource-template) are skipped. MCP-delivered scripts are never runnable: the loader emits noSkillScripts, so a bundled script can at most surface as a readable resource (and only if it matches the resource extensions —.pyis not a default resource extension). The archiveSKILL.mdfrontmatternamemust match the advertised index-entrynameor the skill is skipped. ZIP extraction is hardened: a..path-traversal ("zip-slip") member name raises via_normalize_archive_member_nameand aborts the whole skill (like the file-count/size limits), and file-count / uncompressed-size (_read_member_with_limit) / download-size limits are enforced. Archive behavior is configured witharchive_*constructor kwargs (archive_resource_extensions,archive_resource_search_depth,archive_max_file_count,archive_max_size_bytes,archive_max_uncompressed_size_bytes) — Python uses plain kwargs, not a*Optionsobject as in .NET. A non-"resource not found" error while downloading an archive propagates (so a failedCachingSkillsSourcerefresh does not overwrite a cached list with a partial result). Unlike .NET'sAgentMcpSkillsSourceOptions.RefreshInterval, this source has no built-in refresh interval; wrap it inCachingSkillsSource(..., refresh_interval=...)for caching/refresh. This is a port of .NET PR #6631; theFileSkillsSourcescript_extensions/resource_extensionskwargs default to the built-in tuples and treatNoneas "use defaults" and an empty tuple as "discover none" (an empty tuple previously fell back to defaults).FoundryToolbox.as_skills_provider()forwards matchingarchive_*kwargs to this source. -
SkillsSourcedecorators - Skill sources are composable:SkillsSourceis the abstract base, with concrete sources (InMemorySkillsSource,FileSkillsSource,MCPSkillsSource) and decorators that wrap an inner source —AggregatingSkillsSource(concatenate several sources),FilteringSkillsSource(predicate filter),DeduplicatingSkillsSource(first-wins by name), andCachingSkillsSource(cache the inner source's skills list).DelegatingSkillsSourceis the abstract base for decorators.get_skillstakes aSkillsSourceContext: every source/decorator implementsasync def get_skills(self, context: SkillsSourceContext) -> list[Skill]and forwardscontextto inner sources.SkillsSourceContext(frozen) carries the invokingagent(SupportsAgentRun) and optionalsession(AgentSession | None);SkillsProviderbuilds it frombefore_run'sagent/sessionand passes it into the pipeline.FilteringSkillsSource's predicate is context-aware:Callable[[Skill, SkillsSourceContext], bool](port of .NET #6797). Default caching is applied only to the built-in, context-independent leaf sources: for theSkill/ sequence-of-skills /from_pathsconstructors,SkillsProviderbuildsDeduplicatingSkillsSource(CachingSkillsSource(<file|in-memory leaf>))so expensive filesystem/network discovery runs once. A caller-suppliedSkillsSourceis used as-is — never auto-wrapped in caching or deduplication — because auto-caching a context-aware caller source in a single shared bucket would replay the first invocation's skills for laterSkillsSourceContexts and leak skills across agents/tenants (matches .NET, whose custom-source constructor also adds no caching/dedup). Callers who want caching on a custom pipeline composeCachingSkillsSource(inner, cache_isolation_key_selector=...)themselves.disable_caching=Trueonly affects the built-in leaf caching (it has no effect on a caller-supplied source, which is never cached).CachingSkillsSourceshares a single in-flight fetch across concurrent callers (per cache key) and does not update its cache on a failed fetch, so the next call retries (an initial failure leaves the cache empty; a refresh failure keeps the previously cached list). By default all callers share one cache bucket; passcache_isolation_key_selector=Callable[[SkillsSourceContext], str | None]to cache separately per key (e.g. per agent name) for context-aware inner sources — the key should be low-cardinality and stable, and returningNone(or leaving the selectorNone) uses the shared bucket. By default a cached list never expires; passrefresh_interval=timedelta(...)(port of .NETCachingAgentSkillsSourceOptions.RefreshInterval) to treat a cached list as stale once it is older than the interval so the next call re-queries the inner source (useful when an inner source such asMCPSkillsSourcechanges over the process lifetime; a zero/negative interval makes every result immediately stale, and a failed refresh keeps the prior list and retries). Freshness is measured with a monotonic clock (time.monotonic()).SkillsProvider.__init__/from_pathsexpose acache_refresh_intervalkwarg that is threaded into the built-inCachingSkillsSource(it has no effect on a caller-supplied source or whendisable_caching=True).MCPSkillsSourceandMCPSkillaccept exactly one ofclient(a fixed, already-entered high-levelClientor deprecated caller-ownedClientSession) or the compatibility-namedsession_provider(Callable[[], Client | ClientSession], resolved on every fetch); providing both/neither raisesValueError. The source borrows the supplied connection and never enters or closes it. Usesession_providerwhen an owner replaces its connection over time, so cachedMCPSkills keep fetching through the current normalized connection without readingMCPTool.session. -
MCP archive digests -
MCPSkillsSourceverifies each non-null archivedigestagainst the decoded ZIP bytes after the download-size guard and before extraction. The accepted form issha256:followed by 64 lowercase hexadecimal characters. Omitted/null digests remain supported; malformed values (including non-string JSON), unsupported algorithms, and mismatches warn and skip only that archive. A successfulCachingSkillsSourcerefresh therefore replaces its list without rejected archives; transport errors still propagate and leave the stored cache unchanged. Verification does not apply to lazyskill-mdentries or their supporting resources. A digest only proves consistency with the index, not that the server or skill content is trustworthy.
Model Context Protocol (_mcp.py)
- Client lifecycle design - ADR 0045
defines the ownership boundary. Both framework-created and caller-supplied
_ClientMCPConnectioninstances expose and route operations through a high-levelmcp.Client; theirsessionremainsNone, andis_framework_owneddetermines whether Agent Framework may manage the Client lifecycle. Caller-supplied_SessionMCPConnectioninstances expose and call theirClientSessiondirectly as a deprecated low-level compatibility path. Consequently,MCPTool.sessionis meaningful only for that low-level path. MCPToolconnection state - The private_MCPConnectionProtocol is the normalized tools/prompts/catalog surface._ClientMCPConnectionand_SessionMCPConnectioneach own one lifecycle responsibility;Nonemeans disconnected, and the Client implementation is the single update point for SDK cache policy.MCPStdioTool/MCPStreamableHTTPTool- Supported transport-specific subclasses.MCPWebsocketToolremains only as a deprecated compatibility symbol because MCP v2 removed WebSocket transport; it cannot create a connection.- Argument allowlist (
_prepare_call_kwargs) - Before eachtools/call, kwargs are filtered to an allowlist built from the tool's declared parameters (inputSchema.properties) plus any user-configured extras. The declared half comes from the server's advertised schema, and runtime kwargs (FunctionInvocationContext.kwargs, seeded fromfunction_invocation_kwargs) are merged with the model-supplied arguments upstream in_call_tool_with_runtime_kwargs, so provenance is gone by the time the filter runs. A runtime kwarg is therefore forwarded whenever the server declares a property of that name, without the model mentioning it — the server, not the caller, decides which runtime kwarg names it receives. A tool that declares no usableproperties(including schemas withadditionalProperties: true) forwards only the configured extras._MCP_FRAMEWORK_DENYLISTis a narrow safety net covering only non-serializable framework objects a server declares in its schema (those are dropped); it does not generalize to arbitrary caller-chosen names, and explicit extras always win. The reserved_metakey is never forwarded as an argument; trusted caller/runtime_metais validated as MCP request metadata, model-supplied_metais discarded in generated MCP functions, and metadata precedence is caller/runtime < OpenTelemetry < tools/list metadata. allowed_tools(constructor arg on allMCPToolsubclasses) - Restricts exposed MCP tools by raw remote MCP tool identity. Prefixed local names remain accepted only when the raw remote name already matches its normalized form; normalized/local aliases do not authorize a different raw remote name. Configured allow/approval names must identify at most one raw remote name across loaded tools and prompts: a raw name that overlaps another tool's prefixed alias raisesToolExecutionException. Discovery validates all pages before publishing new functions; a failed reload retains the previous functions and metadata. The allowlist is also revalidated when exposing functions so runtime changes cannot select an ambiguous name. If multiple raw remote tool names map to the same local function name, tool loading raisesToolExecutionExceptioninstead of first-one-wins shadowing.- Progressive MCP disclosure (
use_progressive_disclosure,always_load) - When enabled on anyMCPToolsubclass, the initial model-facing surface is loader tools (list_mcp_tools/load_tool/unload_tool, prefixed bytool_name_prefixwhen configured) plus allowed tools selected byalways_loadand tools loaded earlier on the sameMCPToolinstance.list_mcp_toolsonly reports tools that passallowed_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 explicitload_toolcalls return a model-visible message pointing callers totool_name_prefixor excluding the colliding tool.load_toolaccepts one tool name or a list of tool names and usesFunctionInvocationContext.add_tools(...)so the selected generated MCPFunctionTools become available on the next function-calling iteration while keeping existing approval mode, argument filtering, header-provider runtime kwargs, result parsing, and OTel.unload_toolaccepts 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 inalways_load. Invalidalways_loadentries are ignored like unmatchedallowed_toolsentries. - 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 empty snapshots, while preserving prompts, custom functions, and unchanged tool wrappers (including caller customizations). Removed or replaced tool identities lose their persisted progressive-loaded state; failed refreshes preserve the previous state.
additional_tool_argument_names(constructor arg on allMCPToolsubclasses) - Opt extra argument names back into the allowlist. Accepts aSequence[str](applied to every tool) or aMapping[str, Sequence[str]]keyed by remote tool name, where the reserved key"*"denotes global extras. It is configured only in user code at construction; there is no per-call/runtime override, so a model-issued tool call cannot change which names pass through — but note this constrains the model, not the server, which still widens the effective allowlist through its schema. To use a server that acceptsadditionalProperties: true, list the extra names here and then either (1) manually extend that tool'sinputSchema(via the.functionslist after connecting) so the model is prompted to supply them, or (2) supply the values yourself viafunction_invocation_kwargs. If a normal forwarded argument name is supplied by both the model andfunction_invocation_kwargs, the model-supplied value wins;_metais the exception and only trusted runtime/caller metadata is used.- MCP HTTP header request scoping -
static_headerssupplies fixed, origin-scoped headers without serializing concurrent calls. Generated tool and prompt calls giveheader_provideronly host runtime kwargs, separately from model arguments; directcall_toolcalls give it caller kwargs. Model-over-runtime precedence is confined to outbound tool arguments. Fixed and dynamic headers form the session's complete effective identity (case-insensitive names, case-sensitive values), with dynamic values overriding fixed values of the same name. Agent runs reconcile a connected tool before copying its functions; generated tool and prompt calls perform the same check at invocation. Connected run preparation defers when a provider needs runtime values supplied by invocation middleware; invocation-time resolution remains strict. A different identity waits for in-flight discovery, reconnects framework-created sessions without loading, then refreshes session-derived discovery under the same lock. Because a caller-supplied session's established identity is unknown and the wrapper cannot reconnect it, dynamic header resolution on that wrapper is rejected even while disconnected. Ambient requests retain the bound set. With a sharedhttp_client, processing stays scoped to the originatingMCPStreamableHTTPTool, and every injected header is stripped from cross-origin redirects. The session exit stack removes its request hook after transport shutdown, including failed initialization or discovery, and closes framework-created HTTP clients. Failed discovery resets the connection and discovery flags and rolls back partial function/metadata additions. Framework-created sessions are discarded; constructor-supplied sessions remain caller-owned and reusable across cleanup, close, and reset. - MCP lifecycle caller cancellation - The lifecycle owner skips cancelled queued connect requests and waits for the caller to acknowledge successful setup. If the caller cancels before accepting a newly established connection, the owner tears it down before processing the next request. Cancelling a close waiter does not interrupt teardown, and cancelling a redundant connect does not discard a previously established session.
- Streamable HTTP cookies - Framework-created clients reject response-cookie persistence with or without a
header_provider; explicitCookieheaders fromstatic_headersor a provider remain supported. Caller-provided clients retain their cookie behavior and ownership. Applications requiring cookie persistence must scope clients and MCP sessions to one authenticated principal. Cookie rejection does not isolate MCP protocol sessions or other server-side state. function_invocation_kwargsand MCP servers - That dict is shared across every tool in the run, including every attachedMCPTool, and any name in it reaches a server that declares a matchinginputSchemaproperty.header_providerdoes not mitigate this — it reads the kwargs without consuming them. To keep a credential out of tool arguments, source it outsidefunction_invocation_kwargs: read aContextVarinside the provider (this still allows a different value per request), configure a customhttp_client, or useenvforMCPStdioTool.- Sampling guardrails (
sampling_callback) - Passingclient=advertisesSamplingCapabilityso the server can sendsampling/createMessage. Because remote servers are untrusted (confused-deputy risk), the defaultsampling_callbackis deny-by-default and applies, in order: a per-session rate limit (sampling_max_requests, default_DEFAULT_SAMPLING_MAX_REQUESTS), an approval gate (sampling_approval_callback), and amaxTokenscap (sampling_max_tokens, default_DEFAULT_SAMPLING_MAX_TOKENS). The approval callback (constructor arg on all subclasses; exported type aliasSamplingApprovalCallback) receives the rawCreateMessageRequestParams, may be sync or async, and must return truthy to approve. When it isNone(the default) every sampling request is denied; passlambda params: Trueto restore legacy auto-approve as an explicit opt-in. Requests and denials are logged at WARNING (content is not logged). The per-session counter resets in_reset_session_state. - MCP response caching - High-level Clients use SDK response caching for tool/prompt catalogs and resource reads
regardless of whether Agent Framework or the caller owns the Client, honoring modern server
ttlMs/cacheScopehints. Legacy peers default to zero TTL, caller-suppliedClientSessionconnections stay uncached, and reconnect or effective header-identity changes replace a framework-owned Client's per-Client cache. Agent Framework does not expose shared-store or cache-mode configuration. - MCP Tasks extension - MCP Python SDK 2.2 does not implement the 2026
io.modelcontextprotocol/tasksruntime. Tools that advertiseexecution.taskSupport == "required"are skipped with a warning; optional and task-free tools continue through ordinarytools/call. Restoration of the experimental Tasks API and removed sample is tracked in microsoft/agent-framework#8245.
File Access Harness (_harness/_file_access.py)
AgentFileStore- Abstract async store backing the file-access harness. Implementations exposewrite,read,delete,list_children,file_exists,search, andcreate_directoryover forward-slash relative paths.list_childrenreturns the direct children (files and subdirectories, subdirectories first) asFileStoreEntryinstances;searchaccepts a keyword-onlyrecursiveflag (defaultFalse) and, whenrecursive=True, walks all descendants and returnsfile_namevalues relative to the search directory. The line-numbering contract lives on the base class:split_linespublishes the\n-only keepends split that everyline_numberaddresses,scan_contentis the numbering primitive both shipped stores report through, andsearchis now concrete — it asks the overridablefind_matching_fileshook which files to consider (superset semantics; a backend with a native index overrides it and prunes server-side) and then reads and numbers them itself. A store may still overridesearchoutright, but then it owns numbering: it must reportline_numberas a 1-based coordinate intosplit_linesof the contentreadreturns. Nothing checks that at run time, so a store that numbers differently makes a later edit land on the wrong line silently. The same applies to ReDoS: the grep pattern is model-supplied, sosearchcompiles it through theregexmodule against a single monotonic deadline that bounds the whole scan (CPython'sreholds the GIL for an entire match, soasyncio.wait_foraround it bounds nothing). A store overridingsearchwith bareresilently opts itself back out of that guarantee.InMemoryAgentFileStore- Dict-backed store suitable for tests and lightweight scenarios.FileSystemAgentFileStore- Disk-backed store rooted under a configurable directory. Enforces relative-path normalization, root containment, and rejects symlink/reparse-point segments to prevent escape.FileSearchResult/FileSearchMatch-SerializationMixinDTOs returned bysearch, carrying the matching file name, a context snippet, and the matching lines with 1-based line numbers. Implementers should report each matching line verbatim, including its own terminator, so it can be reused as afile_access_replace_linesnew_line; the pattern itself is matched against the line with its whole terminator removed, so^/$anchor to the line's text on a CRLF file as they already did on an LF one. A custom store populates these DTOs from its ownsearch; the verbatim text is a recommendation, but the line number is not — it must addresssplit_lines.FileStoreEntry-SerializationMixinDTO returned bylist_children, carrying an entrynameandtype("file"or"directory").FileAccessProvider-ContextProviderthat adds shared file-access tools (file_access_write,file_access_read,file_access_read_lines,file_access_delete,file_access_ls,file_access_grep,file_access_replace,file_access_replace_lines) plus default usage instructions to each invocation.file_access_lsenumerates direct children (both files and subdirectories) as{name, type}entries with an optionalglob_pattern, so the agent can walk the tree level by level;file_access_grepsearches recursively from an optional basedirectoryand returns relativefile_namepaths, scoped via anfnmatchglob_pattern(where*crosses/, e.g.*.md,reports/*).file_access_replacesubstitutesold_stringwithnew_string(failing if not found, or if multiple matches andreplace_allis false);file_access_replace_linesreplaces whole 1-based lines with literal text (eachnew_lineincludes its own trailing newline; an emptynew_linedeletes the line, including its line break).file_access_read_linesreturns a 1-based inclusive line range, one line per row as<line_number>\t<line>;end_linemay be omitted to read to the end of the file, and anend_linepast the last line clamps to it. Everything after the tab is verbatim, including the line's own terminator (which therefore doubles as the row separator), so a row's text can be fed straight back as afile_access_replace_linesnew_linewithout losing a\r\n. Its line numbering comes from the same_split_lines_keependssplit asfile_access_replace_linesand as the stores in this package, so with one of those a number reported by grep addresses the same line in all three tools, including the trailing empty line of a newline-terminated file; grep itself runs throughAgentFileStore.search, which must number by the same split but does not inherit it, so a store overridingsearchowns its numbering and nothing verifies it at run time. All tools are registered withapproval_mode="always_require"by default, so every file operation needs host approval. Passdisable_write_tools=Trueto advertise only the read-only tools. To run unattended you can disable approval at the source withdisable_readonly_tool_approval=True(read, read_lines, ls, grep) and/ordisable_write_tool_approval=True(write, delete, replace, replace_lines), which register the affected tools withapproval_mode="never_require"; alternatively, keep approval on and pass one of the static auto-approval rules toToolApprovalMiddleware(viaauto_approval_rules):FileAccessProvider.read_only_tools_auto_approval_ruleapproves only the read-only tools (read, read_lines, ls, grep), whileFileAccessProvider.all_tools_auto_approval_ruleapproves every file-access tool including the write tools. Both rules reject any call carrying aserver_labelso they stay scoped to this provider's local tools and never auto-approve a same-named hosted tool. The tool names are also exposed as class constants (WRITE_TOOL_NAME,READ_TOOL_NAME,READ_LINES_TOOL_NAME,DELETE_TOOL_NAME,LS_TOOL_NAME,GREP_TOOL_NAME,REPLACE_TOOL_NAME,REPLACE_LINES_TOOL_NAME). UnlikeMemoryContextProvider, the store is intentionally shared across sessions and agents; passsession_scoped=True(with an optional explicitscope) to confine tool operations to a working folder derived from the session id or scope via the shared_storage_key_segmentderivation (the provider fails closed when neither is available).
File Memory Harness (_harness/_file_memory.py)
FileMemoryProvider-ContextProviderthat gives an agent a session-scoped, file-based memory backed by the sameAgentFileStoreabstraction. Adds tools (file_memory_write,file_memory_read,file_memory_delete,file_memory_ls,file_memory_grep,file_memory_replace,file_memory_replace_lines) plus default usage instructions. Port of the .NETFileMemoryProvider.- Scoping - Memories are isolated per session by default: each session writes under a working folder derived from
context.session_id. Pass an explicitscope(e.g. a user id) to group memories across sessions, mirroringFoundryMemoryProvider'sscopearg. The scope (or session id) is an opaque namespace key, not a path: it is mapped to exactly one folder via the sharedagent_framework._filesystem._storage_key_segmentderivation, which is injective (except for a collision-resistant digest fallback past a length cap) — two byte-distinct values do not share a working folder, so a caller authorized for one identifier cannot reach another's memories. A multi-segment value such as"tenants/alice"therefore becomes a single encoded folder rather than a nested directory. The provider fails closed (ValueError) when neither ascopenor asession_idis available, because an empty working folder would be the shared store root. Applications should still canonicalize and authorize externally supplied identifiers themselves; the storage mapping is the storage-layer guarantee, not a substitute for that check. - Descriptions & index -
file_memory_writeaccepts an optionaldescription, stored in a companion<stem>_description.mdsidecar. After each write/delete the provider rebuilds a capped (50-entry)memories.mdindex, andbefore_runinjects that index as ausercontext message so the model knows what memories exist. Sidecars and the index are internal files hidden fromfile_memory_ls/file_memory_grepand rejected as write targets. DEFAULT_FILE_MEMORY_SOURCE_ID/DEFAULT_FILE_MEMORY_INSTRUCTIONS- Public defaults for the provider's source id and instruction banner.- Harness wiring -
create_harness_agentincludes theFileMemoryProviderby default; theFileAccessProvideris opt-in and added only when afile_access_storeis supplied (no implicit{cwd}/workingstore is created). Disable file memory viadisable_file_memory; override its backing store viafile_memory_store. When no file-memory store is supplied, the default isFileSystemAgentFileStorerooted at{cwd}/agent-file-memory.create_harness_agentalso wires inMessageInjectionMiddlewareby default (mirroring the .NET harness'sUseMessageInjection); it is always on with no opt-out because it is a no-op when no messages are queued for the session. - Experimental-feature gating -
create_harness_agentitself is released (no longer@experimental), but a few features it can wire in remain experimental or pre-release: background agents (background_agents), file access (file_access_store), looping (loop_should_continue), and the shell tooling (shell_executor, from the pre-releaseagent-framework-toolspackage). Enabling any of them emits a singleExperimentalWarning(naming the responsible parameter). The three experimental harness providers share oneHARNESSdedup key so the downstream experimental provider does not warn a second time; the shell tooling uses a separate dedup key (it is not aHARNESS-decorated feature).
Tool Approval Harness (_harness/_tool_approval.py)
ToolApprovalMiddleware- Opt-in agent middleware that coordinates session-backed approval rules, heuristicauto_approval_rules, queued approval requests, collected approval responses, and streaming/non-streaming approval prompts. Heuristic callbacks receive the underlyingfunction_callcontent.ToolApprovalRule/ToolApprovalState- Serializable state models for standing approvals and queued approval flow.ToolApprovalRule.arguments is Nonemeans a tool-wide rule; an empty dict{}means an exact no-argument call forcreate_always_approve_tool_with_arguments_response.create_always_approve_tool_response/create_always_approve_tool_with_arguments_response- Helpers that return normalfunction_approval_responsecontent withadditional_propertiesmetadata consumed byToolApprovalMiddleware. Standing rules for hosted tools include theserver_labelboundary, so same-named tools on different hosted servers do not share approvals.- Mixed tool-call batches use a default .NET-style bypass in the function invocation loop: when a session is available, approval requests for known non-approval-required tools are treated as already approved, hidden, stored in session state keyed to the visible approval request ids from that batch, and reinjected only when that visible approval flow resumes.
- Approval resume is an immutable response boundary: the function invocation layer normalizes a private copy of
caller messages, returns approved and rejected terminal results in the resumed response (and stream) before any
final assistant message, and does not mutate the caller's approval
Messageor the earlier approval-request response. - Approval/result correlation is occurrence-aware. Provider/service correlation stays in
function_call.call_id, while new locally actionable calls carry one stable Agent Framework occurrence identity infunction_call.id. New local approval request ids use that occurrence id; hosted provider-issued approval ids remain unchanged. Legacy stored pending calls withoutfunction_call.idretain exact request-id binding for one warned compatibility resume. Acall_idmay be reused after a completed round, so approval normalization matches ordered call occurrences and consumes approved results per occurrence rather than using one global result percall_id. All contents produced by one execution remain one result group and are consumed together, including multiple user-input requests. - A local (non-hosted)
function_approval_responseauthorizes execution only when it binds to an approval request recorded in an authoritativeAgentSession. Runs without one drop inbound local approval responses with a warning and execute nothing, so callers must pass the session that issued the request back on the resuming run. An approval request that merely appears in the caller-supplied history is not proof the framework asked for approval. Hosted provider-issued approvals still pass through untouched, and a response already settled by a terminal result is replayed history rather than an authorization, so replaying a completed transcript keeps working without a session. That settled exemption is an allow-list evaluated per response object, not per approval id, because several responses can share one approval id and only the first is eligible to execute. Filtering runs before stateless mixed-batch completeness is enforced, so a dropped response is never counted as an answer. Set thedisable_approval_response_bindingfunction invocation configuration option to restore the previous unbound behavior. - Approval resume keeps terminal
function_resultcontents in tool-role messages and follow-up user-input requests in assistant-role messages, including mixed sibling batches. - Function-call budget accounting counts one unit per executed result group, not per emitted
function_result, so executions that pause for user input still consumemax_function_calls. - Once an invocation limit disables local tools, locally actionable calls and local approval requests are removed from streaming and final output. Provider-executed informational call/result pairs, hosted approval requests, and metadata-only stream updates remain visible.
- Declaration-only streamed calls emit their arguments only from the provider stream. The function layer sends a
metadata-only follow-up (
arguments=None) soidanduser_input_requestsurvive final aggregation without duplicating arguments. function_approval_requestandfunction_approval_responseare control-plane contents. History providers may retain them in their backing store for audit. The baseHistoryProvider.before_runfilters resolved wrappers from later model replay, but preserves unresolved requests/responses until a terminal result or follow-up request closes the occurrence. On unrelated turns the function layer omits the complete pending call batch from model input while retaining it for a later approval response. Providers configured withload_messages=Falsedo not replay history, so this filter is intentionally not invoked.- Reasoning content or opaque reasoning metadata bound to a function call is part of the same logical group as the call and terminal result. Function-loop replay and compaction must preserve that group atomically; adapters should fail before a stateless request when required reasoning cannot be reconstructed.
- Compaction scans assistant function calls and assistant- or tool-role terminal results in transcript/content order,
pairing reused
call_idvalues by ordered unambiguous occurrence. A result links only when exactly one preceding declaration remains unmatched; genuinely ambiguous duplicate declarations stay separate.
Agent Loop (_harness/_loop.py)
AgentLoopMiddleware-AgentMiddlewarethat re-runs an agent in a loop by callingcall_next()repeatedly (the pipeline re-readscontext.messageseach time). One configurable class covers two patterns: a required usershould_continuepredicate (sync or async, the first positional/keyword arg), and a chat-client judge built via the.with_judge(...)factory (a second chat client decides whether the original request was answered; loops while it is not, using a `Ju
Truncated - read the full file at https://github.com/microsoft/agent-framework/blob/44fe223da7ea6853eefb7053e25c2c213a2e5c15/python/packages/core/AGENTS.md.
