Foundry Agentic Loop
GitHubOfficialFirst committed by vieiraaeDistributed by GitHub
- Skill
- Workflow
- Software development
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
foundry-agentic-loop provides a structured framework for developing agentic applications. It supports two primary modes: rapid prototyping for existing projects and Spec-Driven Development (SDD) for new projects requiring full Azure deployment pipelines. The skill manages the lifecycle of agents, toolbox tools, Foundry IQ grounding, and web application components, ensuring consistent architecture, security, and observability across the development process.
What it does
- Orchestrates end-to-end agentic solution development from architecture to Azure deployment.
- Provides a Spec-Driven Development workflow covering Specify, Implement, Verify, and Deploy phases.
- Supports rapid prototyping for existing Foundry projects.
- Manages Foundry hosted agents, toolbox tools, and Foundry IQ grounding configurations.
- Automates deployment of React/FastAPI applications to Azure Container Apps.
- Enforces security best practices through managed identities and least-privilege RBAC.
When to use it
- When building new agentic solutions on Microsoft Foundry that require a structured development lifecycle.
- When you need to deploy agentic applications to Azure using standardized pipelines.
- When prototyping agentic features within an existing Foundry project.
- When you need to integrate Foundry IQ grounding or custom toolbox tools into an agent.
Advantages
- Ensures architectural consistency through a contract-first development approach.
- Automates complex deployment tasks using azd and Bicep infrastructure layers.
- Provides built-in observability via OpenTelemetry and Application Insights integration.
- Maintains project history and lessons learned to improve future development cycles.
- Reduces manual configuration errors by enforcing standardized workspace structures.
Usage examples
- “Start a new agentic project using the SDD workflow.”
- The agent initializes the SDD workflow, creates the necessary project structure, and begins the Specify phase to define the project requirements.
- “Deploy my current Foundry project to Azure.”
- The agent validates the current configuration, runs the deployment pipeline, and reports the status of the Azure Container Apps deployment.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/foundry-agentic-loop/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip foundry-agentic-loop.zip -d .agents/skills
Documentation by vieiraae
Foundry Agentic Loop
Coordinate the solution and use microsoft-foundry for platform operations. Explicit user choices override defaults. Reuse known context, ask only for missing decisions, read only the references a step needs, and report decisions, blockers and endpoints concisely.
Bootstrap (once per session)
Foundry skill. If
microsoft-foundryis unavailable, ask, then install it (copilot plugin install azure@awesome-copilot, orgh skill install microsoft/azure-skills microsoft-foundry --agent github-copilot --scope project) and reload skills.Canvas and workflow. This plugin ships
foundry-agentic-loop-canvasandfoundry-agentic-loop-workflow, listed asfoundry-agentic-loop:<name>or<name>. Callextensions_managewithoperation: "list". Never install extensions from a URL and never edit Copilot settings files. If one is listed under neither name, tell the user which is missing and that it ships with the plugin, then ask before runningcopilot plugin install foundry-agentic-loop@awesome-copilot; after they approve, callextensions_reloadonce. If one is disabled, tell the user to re-enable it in their extension settings and continue in a new session: running sessions keep it disabled, even after a reload. If one failed,inspectit and report its log. Without the canvas, continue in Chat; without the workflow, SDD cannot start, so offer rapid prototyping.Canvas. When work starts from Chat, open it once:
open_canvaswithcanvasId: "foundry-agentic-loop-canvas",instanceId: "foundry-agentic-loop"andinput: { mode }. Prompts that begin[Agentic Loop canvas action]come from the canvas; follow their target, approval and resume instructions literally.
Choose the mode
| Signal | Mode |
|---|---|
Root AGENTS.md has an Agentic Loop section | Its mode. Switch only when the user confirms, then rewrite the section |
| Canvas prompt or explicit choice | As stated |
| Existing Foundry project selected or named; fast prototype; no deployment pipeline needed | Rapid prototyping: rapid.md |
| Spec, new Foundry project, azd or IaC, CI-ready repo or full Azure deployment | SDD: sdd.md |
| Improve, learn from runs, or the canvas improve prompt | Improve: improve.md; measure changes with node scripts/evals.mjs (index, then run --base <commit>; exit 2 means evals are unavailable, so stop) |
| One named SDD phase, with no run active | Its guide (Specify, Implement, Verify or Deploy) with the SDD defaults |
Otherwise ask once with the choices "Rapid prototyping (existing Foundry project)" and "SDD (new project, deployed with azd)".
Lock it in. Before any other workspace write (in the rapid preflight, or just before the SDD workflow starts), upsert the section from agents-md-rapid.md or agents-md-sdd.md into the root AGENTS.md: replace everything between its foundry-agentic-loop begin and end markers, or append it, keeping other content; then read it back. The section routes short commands such as deploy and locks the mode for Chat, the canvas and the workflow. Azure settings go only in .azure/deployment-plan.md, never in AGENTS.md. Improve mode never writes it.
Defaults
Agents: Foundry hosted agents exposing the Responses API, Python 3.13, code deployment. Create them through
microsoft-foundry'sfoundry-agent/create/quick-start-hosted.mdwith the Basic sample, resolved through that skill, never a guessed URL. Use its advanced workflow only when quick-start cannot support a capability, keeping these defaults. Prompt agents only when requested.Framework: the Copilot SDK for agents that use runtime skills (recipe, reference agent); Microsoft Agent Framework for basic agents and explicit workflows. If a workflow also needs skills, clarify. One framework per agent.
Models: rapid keeps the Basic sample's model deployment, or verifies and reuses a supplied one; SDD defaults to
gpt-5.4-miniunless the spec needs otherwise. Run the joint placement preflight in foundry-models.md before creating resources. Never hard-code a replacement or silently duplicate a deployment.Tools and knowledge: one governed Foundry toolbox for built-in tools, MCP connections and agent skills; agents use its endpoint, not hard-coded tool URLs. Private knowledge uses Foundry IQ through the toolbox, with citations for supported claims and a deterministic insufficient-evidence response; test both. Add Search only when needed. Reuse run skills the user names from the run catalog instead of regenerating them.
App: React + Vite, FastAPI and FastMCP (streamable HTTP) on Azure Container Apps. Rapid deploys with
az containerapp up --name <app> --source <dir> --resource-group <rg> --environment <env>; SDD uses azd with amicrosoft.foundrylayer plus a Bicep (AVM) app layer,remoteBuild: trueand one ACR pulled by managed identity. Add services from the reference architecture only when the solution needs them.App access: decide it from the data. When everything the app shows is sample, synthetic or deliberately public, default to no end-user sign-in, even for staff users; services still authenticate with managed identities and need no anonymous-session or identity-verification workarounds. When it shows private, sensitive or user-specific data, ask for the access model before deploying and default to internal ingress or Entra sign-in; anonymous access needs explicit approval. With sign-in, the API pre-authorizes the SPA, the spec states how automated browser tests get a user token, and Implement proves that token path as soon as the app registrations exist.
Identity and safety: managed identities and least-privilege keyless RBAC (contract; preflight with check_rbac_preflight.py). Check management-plane, data-plane and role-assignment rights separately; subscription Owner does not grant Foundry data-plane roles. Plan roles for identities not yet created and verify actual principals after creation. No credentials in browser code or Git; Foundry guardrails on.
Observability: OpenTelemetry from the backend, agents, MCP servers and model calls into one Application Insights connected to the project (observability.md). Sensitive content capture stays off unless approved with redaction and retention controls.
Workspace files
| File | Holds |
|---|---|
AGENTS.md (root) | The mode lock and short-command routes; never Azure settings |
README.md (rapid) or docs/spec.md (SDD, from the spec template) | The contract |
.azure/deployment-plan.md | Every Azure setting, in both modes (template) |
.env (Git-ignored) | What the canvas reads: FOUNDRY_PROJECT (full ARM ID, once validated or created), LOCAL_FRONTEND and DEPLOYED_FRONTEND (verified URLs only). Upsert, keep other keys and read back |
docs/LOOP.md | Lessons (template) |
.agentic-loop/runs/<runId>.json | SDD flight records, written by the workflow |
.devcontainer/devcontainer.json | Optional dev container (asset) |
Working rules
Contract first. Freeze service names, environment variables, protocols, endpoints, schemas, auth, streaming, errors and versions (implementation-contract.md) before parallel work.
Integration first. Pass the hosted integration checkpoint with a minimal agent before building full orchestration, UI or backend: always a model request, plus a toolbox skill load and a safe MCP call only when the architecture needs them. Record excluded capabilities as
N/Awith the reason, never as passed, and never add unused ones to satisfy the checkpoint.Evidence, not signals. HTTP 200, exit 0 or
activenever pass alone; require terminal completion, schema-valid output, execution evidence and correlated traces. Fix with bounded diagnostics, not unchanged redeployments.Wait by completion. Provisioning, deployments, role-assignment propagation and agent readiness end when their command or status check says so: run the command synchronously with a long initial wait, or poll its status every 30-60 s against a stated deadline. Never chain fixed sleeps; keep coding while Azure works.
Subagents. Before the checkpoint, parallelize only research and preflight. After it, give each worker a bounded goal, exclusive workspace-relative files or folders, skill references, verified context, the contract, acceptance checks and stop conditions. One owner (the coordinator, or the SDD phase lead) holds the contract and the shared files:
azure.yaml,infra/,docs/,.env,.azure/,.agentic-loop/,AGENTS.mdand the root lockfiles. Keep teams small, avoid recursive delegation, serialize shared Azure mutations and integrate centrally; worker success is not acceptance. Delegation grants no extra approval. Without subagents, work sequentially and say so.Safety. Reuse resources; confirm billable, security or compliance changes; delete without approval only a resource this build created whose provisioning failed; never sign in for the user; never report an unverified deployment as successful.
Workspace boundary. Builds stay inside the workspace: read lessons only from its own
docs/LOOP.md, scaffold from the Foundry samples and these references, and use code from other folders only when the user names them. Only improve mode reads past runs elsewhere.Work IQ context. Only when the user or a canvas prompt asks for it, query the
workiqMCP server before clarifying questions, fold in only the requirements that matter, cite each by source type and confirm them. Never copy confidential content, personal data or secrets into the workspace; if Work IQ is unavailable or needs consent, say so and continue without it.Companions and SDKs. Verify installed SDK APIs against the latest stable release (or the newest stable one the build's package index serves, recording the gap) and lock versions before generating code; package sources beat stale guidance. Consult the build catalog only for needed capabilities; respect pins, ask before installs and route third-party skill defects upstream.
Lessons
Right after a fix is verified (the failing probe or an equivalent boundary check reruns successfully; an edit, commit or deployment alone is not resolution), upsert a lesson in the workspace's docs/LOOP.md from the template before unrelated work, then read it back. Keep user notes, update matching lessons instead of duplicating them, and never include secrets, raw .env values or payloads. The coordinator, or the SDD phase lead, owns writes; workers report evidence. Lessons never authorize skill edits or weaker gates; improve mode applies them with approval.
Files
- ATTRIBUTION.mdAdded by AutoGineer873 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md12.1 KiB
- assets/agents-md-rapid.md1.1 KiB
- assets/agents-md-sdd.md1.4 KiB
- assets/deployment-plan-template.md3.0 KiB
- assets/devcontainer.json800 B
- assets/loop-template.md1.3 KiB
- assets/spec-template.md4.0 KiB
- evals/evals.json94.0 KiB
- evals/fixtures/improve-history/.agentic-loop/runs/wr_101.json2.4 KiB
- evals/fixtures/improve-history/.agentic-loop/runs/wr_117.json2.4 KiB
- evals/fixtures/improve-history/.agentic-loop/runs/wr_123.json1.6 KiB
- evals/fixtures/improve-history/AGENTS.md1.4 KiB
- evals/fixtures/improve-history/docs/LOOP.md2.0 KiB
- evals/fixtures/rapid-locked/.azure/deployment-plan.md868 B
- evals/fixtures/rapid-locked/.env207 B
- evals/fixtures/rapid-locked/AGENTS.md1.2 KiB
- evals/fixtures/rapid-locked/README.md1010 B
- evals/fixtures/rapid-locked/gitignore41 B
- evals/fixtures/sdd-deployed/.agentic-loop/runs/wr_88.json2.6 KiB
- evals/fixtures/sdd-deployed/.azure/deployment-plan.md1.6 KiB
- evals/fixtures/sdd-deployed/AGENTS.md1.4 KiB
- evals/fixtures/sdd-deployed/docs/spec.md1.9 KiB
- evals/fixtures/sdd-deployed/docs/verify.md374 B
- evals/fixtures/sdd-paused/.agentic-loop/runs/wr_42.json2.9 KiB
- evals/fixtures/sdd-paused/AGENTS.md1.4 KiB
- evals/fixtures/sdd-paused/docs/LOOP.md371 B
- evals/fixtures/sdd-paused/docs/spec.md1.9 KiB
- evals/fixtures/sdd-paused/docs/verify.md322 B
- evals/fixtures/sdd-paused/src/backend/routing.pyScript172 B
- evals/fixtures/sdd-paused/tests/contract/test_routing.pyScript208 B
- evals/fixtures/team-conventions/AGENTS.md224 B
- references/azd-layout.md11.3 KiB
- references/build-skills-catalog.md4.8 KiB
- references/check_rbac_preflight.pyScript18.9 KiB
- references/copilot-sdk-foundry.md16.6 KiB
- references/copilot-sdk-with-toolbox.pyScript14.3 KiB
- references/deploy.md4.4 KiB
- references/foundry-hosted-agent.md6.0 KiB
- references/foundry-iq-grounding.md6.8 KiB
- references/foundry-models.md5.2 KiB
- references/foundry-toolbox.md5.5 KiB
- references/hosted-integration-checkpoint.md13.4 KiB
- references/implement.md5.9 KiB
- references/implementation-contract.md3.7 KiB
- references/improve.md5.0 KiB
- references/observability.md5.9 KiB
- references/rapid.md8.9 KiB
- references/rbac-contract.md9.9 KiB
- references/rbac-preflight.md10.3 KiB
- references/reference-architecture.md3.4 KiB
- references/run-skills-catalog.md3.4 KiB
- references/sdd.md11.1 KiB
- references/specify.md4.4 KiB
- references/verify.md5.3 KiB
- scripts/evals.mjsScript22.0 KiB
references/copilot-sdk-with-toolbox.py
"""Reference hosted agent: GitHub Copilot SDK + Foundry toolbox (tools and skills over MCP).
Reference only: copilot-sdk-foundry.md is the recipe and wins on any conflict. Written against
github-copilot-sdk 1.0.14 and re-checked on 1.0.20; inspect the installed APIs first. Call `run_turn` from the Responses
handler that `azd ai agent init` scaffolds: create one credential and one client at startup and
close them at shutdown, pass the request's `x-agent-foundry-call-id` from the adapter's verified
request-context accessor, and stream the returned tool calls as output items before the message
(foundry-hosted-agent.md). Return a ToolboxError that has a consent_url to the caller as the
answer: the first use of an OAuth connection needs one sign-in per user.
pip install "github-copilot-sdk[telemetry]" azure-identity
Environment (the agent's `env` in azure.yaml; FOUNDRY_* and AGENT_* are platform-reserved):
TOOLBOX_ENDPOINT Consumer URL <project>/toolboxes/<name>/mcp?api-version=v1, mapped
from TOOLBOX_<NAME>_MCP_ENDPOINT; it serves the default version.
MODEL_API_BASE_URL The discovered .../openai/v1/ base and its deployment. Required
AZURE_AI_MODEL_DEPLOYMENT_NAME when hosted; locally, unset means the Copilot default model.
COPILOT_OTLP_ENDPOINT Optional OTLP HTTP receiver for runtime spans.
Skills attached to the toolbox are MCP resources (skill://<name>/SKILL.md) that follow each
skill's default version, so publishing a skill needs no redeploy. For multi-file skills, or
skills outside a toolbox, use the Skills API download in microsoft-foundry. Verify that served
bodies keep their frontmatter; load_skills rebuilds it when missing.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
import tempfile
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import httpx
from azure.core.credentials_async import AsyncTokenCredential
from azure.identity.aio import DefaultAzureCredential
from copilot import CopilotClient, SessionEventType, Tool, ToolInvocation, ToolResult
from copilot.generated.rpc import PermissionDecisionApproveOnce, PermissionDecisionReject
from copilot.generated.session_events import PermissionRequestCustomTool, PermissionRequestRead
from copilot.session import ProviderConfig, ProviderTokenArgs
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
log = logging.getLogger("agent")
tracer = trace.get_tracer(__name__)
SCOPE = "https://ai.azure.com/.default" # model and toolbox audience; cognitiveservices gets 401
TOOLBOX_ENDPOINT = os.environ["TOOLBOX_ENDPOINT"]
MODEL_BASE_URL = os.getenv("MODEL_API_BASE_URL")
MODEL_DEPLOYMENT = os.getenv("AZURE_AI_MODEL_DEPLOYMENT_NAME")
if bool(MODEL_BASE_URL) != bool(MODEL_DEPLOYMENT):
# One without the other would silently fall back to the Copilot default model.
raise RuntimeError("Set both MODEL_API_BASE_URL and AZURE_AI_MODEL_DEPLOYMENT_NAME, or neither.")
WRITABLE = Path(tempfile.gettempdir()) # hosted containers are read-only except the temp dir
SKILL_URI = re.compile(r"skill://([A-Za-z0-9_-]+)/SKILL\.md")
TURN_TIMEOUT = 300.0
@dataclass
class ToolCall:
"""One toolbox call, emitted as function_call and function_call_output items."""
call_id: str
name: str
arguments: str
output: str
@dataclass
class Turn:
text: str
tool_calls: list[ToolCall] = field(default_factory=list)
class ToolboxError(RuntimeError):
"""A toolbox JSON-RPC error; `consent_url` is set when a connection needs user consent."""
def __init__(self, message: str, consent_url: str | None = None) -> None:
super().__init__(message)
self.consent_url = consent_url
def _toolbox_error(error: dict[str, Any]) -> ToolboxError:
message = str(error.get("message", ""))
if error.get("code") == -32006 and "{" in message:
try: # -32006 wraps per-source errors as JSON after a human-readable prefix
for source in json.loads(message[message.index("{") :]).get("errors", []):
nested = source.get("error") or {}
if nested.get("code") == "CONSENT_REQUIRED":
url = nested.get("message")
name = source.get("name", "A toolbox connection")
return ToolboxError(f"{name} needs consent: open {url}, sign in, then retry.", url)
except (ValueError, AttributeError):
pass
return ToolboxError(f"Toolbox error {error.get('code')}: {message or 'unknown'}")
class _Bearer(httpx.Auth):
"""Adds a token to every request; Azure Identity caches and renews it."""
def __init__(self, credential: AsyncTokenCredential) -> None:
self._credential = credential
async def async_auth_flow(self, request: httpx.Request):
request.headers["Authorization"] = f"Bearer {(await self._credential.get_token(SCOPE)).token}"
yield request
class McpBridge:
"""Request-scoped JSON-RPC client for the toolbox MCP endpoint; initialize is optional."""
def __init__(self, credential: AsyncTokenCredential, call_id: str | None) -> None:
headers = {"Foundry-Features": "Toolboxes=V1Preview"}
if call_id: # forward the caller context unchanged; never fabricate one
headers["x-agent-foundry-call-id"] = call_id
self._http = httpx.AsyncClient(auth=_Bearer(credential), headers=headers, timeout=60.0)
self._next_id = 0
async def __aenter__(self) -> McpBridge:
return self
async def __aexit__(self, *_exc: object) -> None:
await self._http.aclose()
async def rpc(self, method: str, params: dict[str, Any], target: str = "") -> dict[str, Any]:
"""One JSON-RPC call in an MCP client span that records no arguments or results."""
self._next_id += 1
payload = {"jsonrpc": "2.0", "id": self._next_id, "method": method, "params": params}
name = f"{method} {target}".strip()
with tracer.start_as_current_span(
name, record_exception=False, set_status_on_exception=False
) as span:
span.set_attribute("mcp.method.name", method)
if method == "tools/call":
span.set_attribute("gen_ai.tool.name", target)
try:
response = await self._http.post(TOOLBOX_ENDPOINT, json=payload)
response.raise_for_status()
body = response.json()
if "error" in body:
raise _toolbox_error(body["error"])
except Exception as exc:
span.set_status(Status(StatusCode.ERROR))
span.set_attribute("error.type", type(exc).__name__)
raise
return body.get("result") or {}
def _call_handler(toolbox: McpBridge, mcp_name: str, calls: list[ToolCall]):
async def handler(invocation: ToolInvocation) -> ToolResult:
arguments = invocation.arguments if isinstance(invocation.arguments, dict) else {}
try:
result = await toolbox.rpc("tools/call", {"name": mcp_name, "arguments": arguments}, mcp_name)
except Exception as exc: # report to the model; it can retry or explain
output, outcome = str(exc), ToolResult(result_type="failure", error=str(exc))
else:
texts = [c.get("text", "") for c in result.get("content", []) if c.get("type") == "text"]
output = "\n".join(t for t in texts if t) or json.dumps(result)
failed = bool(result.get("isError"))
outcome = ToolResult(
text_result_for_llm=output,
result_type="failure" if failed else "success",
error=output if failed else None,
)
calls.append(ToolCall(invocation.tool_call_id, mcp_name, json.dumps(arguments), output))
return outcome
return handler
def toolbox_tools(toolbox: McpBridge, listed: list[dict[str, Any]], calls: list[ToolCall]) -> list[Tool]:
"""Wrap each tools/list entry as an SDK tool; MCP-sourced names look like label___tool."""
tools: dict[str, Tool] = {}
sources: dict[str, str] = {}
for spec in listed:
mcp_name = spec["name"]
name = re.sub(r"[.-]", "_", mcp_name) # SDK tool names reject dots and hyphens
if name in sources:
# Dropping one would silently change the agent's capabilities; rename a tool instead.
raise ValueError(f"Toolbox tools {sources[name]!r} and {mcp_name!r} both map to {name!r}.")
sources[name] = mcp_name
tools[name] = Tool(
name=name,
description=spec.get("description") or mcp_name,
parameters=spec.get("inputSchema") or {"type": "object", "properties": {}},
handler=_call_handler(toolbox, mcp_name, calls),
)
return list(tools.values())
async def load_skills(toolbox: McpBridge, skills_dir: Path) -> list[str]:
"""Write each toolbox skill to <skills_dir>/<name>/SKILL.md for the SDK skill loader."""
names: list[str] = []
for resource in (await toolbox.rpc("resources/list", {})).get("resources", []):
match = SKILL_URI.fullmatch(resource.get("uri", ""))
if not match:
continue # skill://index.json, archives and other resources
name = match.group(1)
read = await toolbox.rpc("resources/read", {"uri": resource["uri"]}, name)
body = "".join(c.get("text", "") for c in read.get("contents", []))
if not body.lstrip().startswith("---"):
description = json.dumps(resource.get("description") or name)
body = f"---\nname: {name}\ndescription: {description}\n---\n\n{body}"
(skills_dir / name).mkdir(parents=True, exist_ok=True)
(skills_dir / name / "SKILL.md").write_text(body, encoding="utf-8")
names.append(name)
return names
def model_provider(credential: AsyncTokenCredential) -> ProviderConfig:
async def refresh_token(_request: ProviderTokenArgs) -> str:
return (await credential.get_token(SCOPE)).token
return {
"type": "openai",
"base_url": MODEL_BASE_URL,
"wire_api": "responses",
"bearer_token_provider": refresh_token,
}
def least_privilege(tool_names: set[str], skills_dir: Path) -> Callable[[Any, Any], Any]:
"""Approve this turn's toolbox tools and reads of its skills; reject everything else."""
def decide(request: Any, _invocation: Any) -> Any:
if isinstance(request, PermissionRequestCustomTool) and request.tool_name in tool_names:
return PermissionDecisionApproveOnce()
if isinstance(request, PermissionRequestRead):
if Path(request.resolved_path or request.path).resolve().is_relative_to(skills_dir):
return PermissionDecisionApproveOnce()
return PermissionDecisionReject(feedback="Not permitted for this agent.")
return decide
def log_event(event: Any) -> None:
"""Log safe identifiers only: never prompts, arguments, results or caller context."""
data = event.data
if event.type == SessionEventType.SESSION_ERROR:
log.error(
"session error type=%s code=%s status=%s request=%s",
data.error_type, data.error_code, data.status_code, data.service_request_id,
)
elif event.type == SessionEventType.TOOL_EXECUTION_START:
log.info("tool start %s id=%s", data.tool_name, data.tool_call_id)
elif event.type == SessionEventType.TOOL_EXECUTION_COMPLETE:
log.info("tool done id=%s success=%s", data.tool_call_id, data.success)
def new_client() -> CopilotClient:
"""One Copilot runtime per process."""
options: dict[str, Any] = {}
if not os.access(Path.home(), os.W_OK): # session state defaults to ~/.copilot
options["base_directory"] = str(WRITABLE / "copilot")
if endpoint := os.getenv("COPILOT_OTLP_ENDPOINT"):
options["telemetry"] = {
"otlp_endpoint": endpoint,
"otlp_protocol": "http/protobuf",
"exporter_type": "otlp-http",
"capture_content": False,
}
return CopilotClient(**options)
async def run_turn(
client: CopilotClient, credential: AsyncTokenCredential, prompt: str, call_id: str | None = None
) -> Turn:
"""Run one request with its own toolbox connection, skills directory and session."""
calls: list[ToolCall] = []
headers = {"x-agent-foundry-call-id": call_id} if call_id else None
options: dict[str, Any] = {}
if MODEL_BASE_URL:
options = {"provider": model_provider(credential), "model": MODEL_DEPLOYMENT}
async with McpBridge(credential, call_id) as toolbox:
tools = toolbox_tools(toolbox, (await toolbox.rpc("tools/list", {})).get("tools", []), calls)
with tempfile.TemporaryDirectory(prefix="turn-", dir=WRITABLE) as workdir:
skills_dir = Path(workdir).resolve() / "skills"
await load_skills(toolbox, skills_dir)
async with await client.create_session(
**options,
tools=tools,
skill_directories=[str(skills_dir)],
working_directory=workdir,
on_permission_request=least_privilege({tool.name for tool in tools}, skills_dir),
on_event=log_event,
) as session:
try:
reply = await session.send_and_wait(
prompt, request_headers=headers, timeout=TURN_TIMEOUT
)
except TimeoutError:
await session.abort() # the timeout alone leaves the turn running
raise
if reply is None or not reply.data.content:
raise RuntimeError("The session ended without an assistant message.")
return Turn(reply.data.content, calls)
async def main() -> None:
"""Local smoke run: `az login`, set TOOLBOX_ENDPOINT, optionally the model pair."""
logging.basicConfig(level=logging.INFO)
async with DefaultAzureCredential() as credential, new_client() as client:
try:
turn = await run_turn(client, credential, "Which tools and skills can you use? Be brief.")
except ToolboxError as exc:
if exc.consent_url is None:
raise
print(exc)
return
for call in turn.tool_calls:
print(f"tool {call.name}: {len(call.output)} chars")
print(turn.text)
if __name__ == "__main__":
asyncio.run(main())
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
vieiraae
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/foundry-agentic-loop · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- vieiraae
AutoGineer is not affiliated with or endorsed by vieiraae or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download foundry-agentic-loop.zip