maf-foundry-agent
Skill2 starsChanged 4 months agoMITView on GitHub
Building the local MAF reasoning agent against a Microsoft Foundry project endpoint: agent factories, function tools, skills, sessions, middleware, and Azure AI Search retrieval. Load for work under src/agents, src/tools, or src/retrieval. NOT for chunking, embedding, populating, or inspecting a Search index - load ai-search for that.
- Reads credentials
- Installs packages
In this repository19 other files it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/repository.mdcCursor rule
- ai-searchSkill
- maf-agent-configSkill
- maf-dev-loopSkill
- maf-foundry-agentSkill
- maf-multi-agent-workflowsSkill
- maf-voice-agentSkill
- mermaid-diagramsSkill
- skill-pack-auditSkill
- voicelive-realtimeSkill
- ai-searchSkill
- maf-agent-configSkill
- maf-dev-loopSkill
- maf-multi-agent-workflowsSkill
- maf-voice-agentSkill
- mermaid-diagramsSkill
- skill-pack-auditSkill
- voicelive-realtimeSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 2 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 115
Always export a build_<name>_agent(...) -> Agent factory.
- Distinctive: line 154
Keep session persistence in application-owned storage only if the application already has it.
- Distinctive: line 191
Prefer this over hand-rolled orchestration for simple delegation.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
MAF on Foundry — Agent Patterns
Depth lives in references. Load one only when the task needs it.
| Task | Reference |
Write a @tool, author an Agent Skill, set approval modes | references/tools-and-skills.md |
Session history and custom ContextProvider | references/memory-and-context.md |
| Ground the agent in Azure AI Search | references/retrieval.md |
Creating, populating, and validating the Azure AI Search index is owned by the separate
ai-search skill.
Install
python -m pip install agent-framework agent-framework-foundry agent-framework-declarative azure-identityChoose the chat client by credential
Pick the client from the credential you actually hold. Getting this wrong surfaces as a 403
on the first model call, long after startup looked healthy.
| You have | Client | Endpoint |
Entra token and Foundry User on the resource | FoundryChatClient | project endpoint |
| Resource API key only | OpenAIChatClient | <resource>/openai/v1/ |
FoundryChatClient takes credential: TokenCredential | AsyncTokenCredential — it has no
api_key parameter, so a key cannot be substituted. It also calls agents/write on the
project, which Owner does not grant because that is a data action, not a control action.
# Entra: project endpoint
from agent_framework.foundry import FoundryChatClient
client = FoundryChatClient(
project_endpoint=settings.foundry_project_endpoint,
model=config.model.deployment,
credential=credential,
)# API key only: resource endpoint
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient(
config.model.deployment,
api_key=settings.foundry_api_key,
base_url=settings.foundry_openai_base_url, # <resource>/openai/v1/
)The key path must use a base_url ending in /openai/v1/. Agent Framework calls the Responses
API, and pairing azure_endpoint= with a dated api_version fails with
400 API version not supported. Derive the resource endpoint by stripping /api/projects/...
from the project endpoint. Credentials accepted by the VoiceLive websocket are owned by
voicelive-realtime.
Annotate factories and builders as BaseChatClient so either client mounts unchanged.
Baseline agent
Instructions, model, and the tool list come from config/agents/<name>.yaml, a MAF-native
kind: Prompt document — see maf-agent-config. Do not write
literal instructions or tool lists into src/, and do not hand-roll a parser for that
document: AgentFactory already does it.
import os
from agent_framework import Agent
from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential
from dotenv import load_dotenv
load_dotenv() # Agent Framework never does this for you
def build_concierge_agent(factory: AgentFactory, path, **deps) -> Agent:
agent = factory.create_agent_from_yaml_path(path)
agent.context_providers.extend(deps.get("context_providers", []))
return agent
async def main() -> None:
async with AzureCliCredential() as credential:
factory = AgentFactory(
client_kwargs={
"credential": credential,
"project_endpoint": os.environ["FOUNDRY_PROJECT_ENDPOINT"],
},
bindings=TOOL_BINDINGS,
safe_mode=False,
)
agent = build_concierge_agent(factory, "config/agents/concierge.yaml")
session = agent.create_session()
print(await agent.run("Do I have a booking under ABC123?", session=session))Always export a build_<name>_agent(...) -> Agent factory. It is what lets the voice loop,
DevUI, and tests mount the same agent. Module-level construction breaks DevUI reload and
forces network access at import time.
AgentFactory returns a plain Agent. Retrieval providers, middleware, and approval wrapping
are attached by the factory function afterwards — agent.context_providers and
agent.middleware are public mutable lists. create_agent_from_yaml_path is sync;
create_agent_from_yaml_path_async exists for async call sites and is preferred inside the
voice loop's setup.
A declared function tool whose binding name is missing from bindings is constructed with
func=None and fails silently at call time. Assert the mapping is total when you build.
Supported capabilities
- Local
@toolfunctions and Agent Skills. - Local middleware and multi-agent composition.
- Azure AI Search context providers and direct retrieval using
AZURE_SEARCH_API_KEY. AgentSessionfor per-conversation state.
Project toolboxes, hosted tools, Foundry memory stores, project connections, and hosted agents are outside the resource and authentication contract.
Sessions and conversation state
from agent_framework import AgentSession
session = agent.create_session()
async for update in agent.run("...", session=session, stream=True):
print(update.text, end="")
serialized = session.to_dict()
session = AgentSession.from_dict(serialized)- One session per user conversation. Never share a session across users.
- Authorize resumed state. A serialized session handle from a client request is untrusted; verify the authenticated caller owns it before restoring, or you have an IDOR.
- Keep session persistence in application-owned storage only if the application already has it. This seed does not provision a session database.
Middleware
Three kinds, all composable, same shape (receive context, await next(context)):
| Kind | Context | Typical use |
| Agent | AgentContext | auth, rate limiting, request/response logging, termination |
| Function | FunctionInvocationContext | tool-level approval, arg validation, retries |
| Chat | ChatContext | prompt shaping, model fallback, token accounting |
from agent_framework import agent_middleware, AgentContext
@agent_middleware
async def require_tenant(context: AgentContext, next):
if not context.metadata.get("tenant_id"):
context.terminate("Missing tenant.")
return
await next(context)Order is outside-in then inside-out: A1 → A2 → F1 → F2 → agent → F2 → F1 → A2 → A1.
Skipping await next(context) is the supported way to deny a request.
Agents as tools
researcher_tool = researcher.as_tool(
name="research", description="Research a topic and return a summary",
arg_name="query", arg_description="What to research",
)
coordinator = Agent(client=client, instructions="Delegate research.", tools=[researcher_tool])Prefer this over hand-rolled orchestration for simple delegation. Anything beyond one delegated call — a second participant, an orchestration pattern, graph structure, checkpointing, or human-in-the-loop gates — is maf-multi-agent-workflows.
Credential handling
The project endpoint does not accept the Foundry resource API key through
FoundryChatClient. Inject a token credential into the client factory and never derive
identity from a request or transcript. Keep .env gitignored.
Anti-patterns
| Pattern | Verdict |
A hand-rolled parser for config/agents/*.yaml | AgentFactory already loads that schema |
A function tool declared in YAML with no entry in bindings | Built with func=None; the model calls a no-op |
API key passed to FoundryChatClient / AIProjectClient | Project clients require a token credential |
| Agent constructed at module scope | Breaks DevUI reload; network at import |
Missing load_dotenv() | Agent Framework does not load .env |
| Resuming a session ID straight from a client request | IDOR — authorize ownership first |
| Credential or key embedded in code, YAML, or a tool argument | Inject it at the client boundary |
| Project connection, memory store, App Insights, Storage, Cosmos DB, Redis, or Content Understanding | Adds a forbidden resource or auth path |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

