Microsoft Agent Framework
An agent in Python or .NET with an identity in the LumoAuth registry, whose tools ask LumoAuth before they run.
What it shows
- The agent signs in to LumoAuth as itself, with its client ID and secret. Python asks for the token at the start, and .NET on the first call.
- Each tool asks LumoAuth first, with the Ask API, for the action of the tool.
- LumoAuth allows the agent to read the contract, because the agent holds
contracts:read. - LumoAuth refuses to let it sign. The tool returns the reason to the model and does nothing, and the model tells the person.
Before you start
- An agent with a client ID and secret. The setup script below registers "Contract desk agent", which may read contracts and nothing else.
- For Python: Python 3.11 or later. For .NET: the .NET 10 SDK, which runs a single
.csfile. - An OpenAI API key for the model.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
AGENT_CLIENT_ID | The client ID of the agent "Contract desk agent". The setup script prints it. |
AGENT_CLIENT_SECRET | Its client secret. The setup script prints it. |
OPENAI_API_KEY | The API key of your OpenAI account, for the model. |
OPENAI_MODEL | Optional. The model. Default: gpt-5-mini. |
The setup script registers "Contract desk agent" with the capability contracts:read. Its API key needs the scopes admin:agents:read and admin:agents:write.
node frameworks/ms-agent-framework/setup.mjs
setup.mjs
// Registers the agent of this recipe, "Contract desk agent", which may read
// contracts and nothing else, and prints its client ID and secret. Run it
// again at any time.
//
// node frameworks/ms-agent-framework/setup.mjs
//
// The API key needs the scopes admin:agents:read and admin:agents:write.
import { call, ensure, printEnv } from '../../_lib/admin.mjs';
const agent = await ensure('/admin/agents', (a) => a.name === 'Contract desk agent', {
name: 'Contract desk agent',
description: 'Reads contracts for the legal team. It may not sign them.',
identityType: 'client_secret',
capabilities: ['contracts:read'],
});
// LumoAuth shows a secret once, in the answer that creates it. On a second
// run the script therefore asks for a new secret, and the old one stops.
const secret =
agent.clientSecret ??
(await call('POST', `/admin/agents/${agent.agentId}/rotate-credentials`)).data.clientSecret;
console.log(`Agent "${agent.name}" (${agent.agentId}) holds: contracts:read`);
printEnv({ AGENT_CLIENT_ID: agent.agentId, AGENT_CLIENT_SECRET: secret });
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The order of the tool calls and the last line depend on the model.
- Python
- C#
"""A Microsoft Agent Framework agent with an identity in LumoAuth. Each tool
asks LumoAuth before it runs, and a refused tool returns the reason.
cd frameworks/ms-agent-framework/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py
"""
import asyncio
import json
import os
from typing import Annotated
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from lumoauth import LumoAuthAgent
from pydantic import Field
# The agent signs in as itself, with the client credentials grant.
# Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
lumo = LumoAuthAgent()
lumo.authenticate()
CONTRACTS = {"CTR-2048": {"party": "Northwind Labs", "type": "supply agreement", "status": "awaiting signature"}}
def refusal(tool_name: str, action: str, **context) -> str | None:
"""Asks LumoAuth whether the agent may do the action. Returns the reason of a refusal."""
answer = lumo.ask(action, context)
print(f"{tool_name}: {action} {'allowed' if answer['allowed'] else 'refused'}")
return None if answer["allowed"] else answer["reason"]
def read_contract(contract_id: Annotated[str, Field(description="The ID of the contract")]) -> str:
"""Read one contract: the other party, the type and the status."""
if reason := refusal("read_contract", "contracts:read", contract=contract_id):
return f"Refused by LumoAuth: {reason}"
return json.dumps(CONTRACTS.get(contract_id, {}))
def sign_contract(contract_id: Annotated[str, Field(description="The ID of the contract")]) -> str:
"""Sign a contract in the name of the company."""
if reason := refusal("sign_contract", "contracts:sign", contract=contract_id):
# The model reads the reason and can tell the person.
return f"Refused by LumoAuth: {reason}"
return f"Signed {contract_id}"
agent = Agent(
client=OpenAIChatClient(model=os.environ.get("OPENAI_MODEL", "gpt-5-mini")),
name="Contract desk",
instructions="You help the legal team with contracts. If LumoAuth refuses a tool, say why.",
tools=[read_contract, sign_contract],
)
async def main() -> None:
response = await agent.run("Read contract CTR-2048, then sign it.")
print(f"model: {response.text}")
if __name__ == "__main__":
asyncio.run(main())
agent-framework>=1.26
lumoauth>=1.7.0
cd frameworks/ms-agent-framework/python
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python agent.py
Compiles. Not run against an organization. The agent was built and its two tools were called directly against an organization. The agent did not run with a model: it needs a model API key.
#:package LumoAuth@1.7.0
#:package Microsoft.Agents.AI.OpenAI@1.28.0
#:property PublishAot=false
// A Microsoft Agent Framework agent with an identity in LumoAuth. Each tool
// asks LumoAuth before it runs, and a refused tool returns the reason.
//
// dotnet run frameworks/ms-agent-framework/csharp/ContractDesk.cs
using System.ComponentModel;
using System.Text.Json;
using LumoAuth;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
// The agent signs in as itself, with the client credentials grant. The token
// is fetched on first use and renewed. Reads LUMOAUTH_URL, LUMOAUTH_ORG_ID,
// AGENT_CLIENT_ID and AGENT_CLIENT_SECRET.
var lumo = LumoAgent.FromEnvironment();
var contracts = new Dictionary<string, object>
{
["CTR-2048"] = new { party = "Northwind Labs", type = "supply agreement", status = "awaiting signature" },
};
// Asks LumoAuth whether the agent may do the action. Returns the reason of a refusal.
async Task<string?> Refusal(string tool, string action, string contractId)
{
var answer = await lumo.AskAsync(action, new Dictionary<string, object> { ["contract"] = contractId });
Console.WriteLine($"{tool}: {action} {(answer.Allowed ? "allowed" : "refused")}");
return answer.Allowed ? null : answer.Reason;
}
[Description("Read one contract: the other party, the type and the status.")]
async Task<string> ReadContract([Description("The ID of the contract")] string contractId) =>
await Refusal("read_contract", "contracts:read", contractId) is { } reason
? $"Refused by LumoAuth: {reason}"
: JsonSerializer.Serialize(contracts.GetValueOrDefault(contractId));
[Description("Sign a contract in the name of the company.")]
async Task<string> SignContract([Description("The ID of the contract")] string contractId) =>
// The model reads the reason and can tell the person.
await Refusal("sign_contract", "contracts:sign", contractId) is { } reason
? $"Refused by LumoAuth: {reason}"
: $"Signed {contractId}";
AIAgent agent = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
.GetChatClient(Environment.GetEnvironmentVariable("OPENAI_MODEL") ?? "gpt-5-mini")
.AsIChatClient()
.AsAIAgent(
name: "Contract desk",
instructions: "You help the legal team with contracts. If LumoAuth refuses a tool, say why.",
tools:
[
AIFunctionFactory.Create(ReadContract, name: "read_contract"),
AIFunctionFactory.Create(SignContract, name: "sign_contract"),
]);
Console.WriteLine($"model: {await agent.RunAsync("Read contract CTR-2048, then sign it.")}");
dotnet run frameworks/ms-agent-framework/csharp/ContractDesk.cs
Compiles. Not run against an organization. The program compiled, and its two tools were called against an organization from a copy without the model call. The agent did not run with a model: it needs a model API key.
Check the result
read_contract: contracts:read allowed
sign_contract: contracts:sign refused
model: Contract CTR-2048 is a supply agreement with Northwind Labs, awaiting signature. I could not sign it: LumoAuth refused, because the agent lacks the capability contracts:sign.
- The audit log shows
agent.capability_check_deniedforcontracts:sign, with the agent as the actor. - Add the capability
contracts:signto the agent in the portal, and run again: the tool signs.
Limits
- The capabilities of the agent are the same for every person who uses it. For an action that a person must approve, see the LangGraph recipe or Ask a person for a permission, for one task.
- In .NET, the extension
AsAIAgent()takes anIChatClient. The OpenAI chat client becomes one withAsIChatClient(). - To link the audit rows to the trace of the run, see Link agent actions to traces.