The first article in this series made the case for AI managed agents in NHS organisations. The second explained how they are built — the agent definition file, N8N orchestration, the Anthropic API, and the compliance framework. This third article is different: it is a working implementation.
Everything described here exists as actual, importable files. A real workflow. A real agent definition. A real knowledge base. Built around a fictional NHS ICB — NHS Westshire ICB — but structured so that any NHS organisation can adapt it by replacing the knowledge base files with their own data.
The system described handles one of the most time-consuming and legally demanding administrative functions in any NHS organisation: Freedom of Information Act 2000 requests. The FOI Agent receives requests, classifies them, searches its knowledge base, drafts a response, and routes everything to the FOI Lead for review — all within minutes of an email arriving.
All files referenced in this article are available in the companion GitHub repository under NHSManagedAgents/. The repository includes the agent definition, knowledge base, N8N workflow JSON files (importable directly), setup guides, and 25 sample test requests.
1What This Example Builds
The FOI Agent handles the complete administrative lifecycle of a Freedom of Information request — from the moment an email arrives at the ICB's FOI inbox to the moment a draft response lands in the FOI Lead's email for approval. Here is what it does in sequence:
foi@westshire.icb.nhs.uk every 2 minutes via IMAP. New unread emails are picked up, marked as read, and passed to the pipeline. Web form submissions arrive via webhook in real time.FOI-YYYY-NNNN. The statutory 20-working-day deadline is calculated in JavaScript, skipping weekends and UK bank holidays, to produce an exact calendar date.What the agent does not do: It never sends a final response to the requester. It never makes a final disclosure decision. It never applies an exemption without the FOI Lead's approval. Every substantive decision is made by a human — the agent handles everything up to that decision point.
2Repository Structure
The repository is organised so that each file has a single, clear purpose. The separation between the agent definition, the knowledge base, the workflows, and the guides makes it easy to adapt any component without touching the others.
| File | Purpose | Used By |
|---|---|---|
agents/foi-agent.md |
Agent identity, rules, autonomous actions, escalation logic, legal framework | Claude API system prompt |
knowledge-base/icb-profile.md |
Complete ICB factual reference — budget, staff, contracts, properties, governance | Claude API (analysis prompt) |
knowledge-base/foi-disclosure-log.md |
25 previous FOI responses — helps identify duplicates, ensures consistency | Claude API (analysis prompt) |
knowledge-base/foi-exemptions-reference.md |
FOIA 2000 and EIR exceptions reference with NHS-specific guidance and PIT guidance | Claude API (analysis prompt) |
n8n-workflows/foi-email-workflow.json |
15-node N8N workflow for email-based FOI processing (importable) | N8N workflow engine |
n8n-workflows/foi-form-workflow.json |
7-node N8N workflow for web form FOI submissions (importable) | N8N workflow engine |
.env.example |
All required environment variables with descriptions | System administrator |
guides/01-imap-email-setup.md |
IMAP configuration for Gmail, Microsoft 365, and NHS.net | System administrator |
guides/02-n8n-setup.md |
N8N Docker installation, credential setup, NHS Azure deployment notes | System administrator |
guides/03-anthropic-api-setup.md |
API key creation, cost estimates, prompt caching, data sovereignty notes | Developer |
guides/04-testing-guide.md |
Testing procedures, expected outputs, regression checklist (10 items) | Developer / FOI Lead |
examples/sample-foi-requests.md |
25 realistic FOI request emails for testing all agent behaviours | Developer / FOI Lead |
To adapt this for your organisation: replace the three knowledge base files with your ICB's data, update the YAML header in agents/foi-agent.md with your ICB's details and FOI Lead's contact information, and follow the setup guides. The N8N workflows and the agent logic do not need to change.
3The FOI Agent Definition
The agent definition file (agents/foi-agent.md) is the single source of truth for how the agent behaves. It follows the same 10-section structure used by every other agent in the NHS Managed Agents architecture. The YAML front matter identifies the agent; the numbered sections define everything else.
--- agent_id: foi-agent agent_name: Freedom of Information & EIR Agent version: 1.0 directorate: SFR (Strategy, Finance & Resources) email_address: foi@westshire.icb.nhs.uk supervising_human: Head of Corporate Affairs (FOI Lead) escalation_turnaround_hours: 2 last_updated: 2026-05-14 --- # 1. Identity & Purpose You are the Freedom of Information & EIR Agent for NHS Westshire Integrated Care Board. You operate under direct supervision of the Head of Corporate Affairs and FOI Lead, Diane Okafor... # 2. What You Can Do Autonomously - Receive and classify all requests within 2 hours - Generate case references: - Calculate 20-working-day deadline (skip weekends, UK bank holidays) - Search knowledge base for responsive information - Check disclosure log for duplicates - Draft acknowledgement and draft response - Send automated acknowledgement to requester - Send internal alert to FOI Lead with draft - Log all cases in the case register - Send Day 15 deadline reminders # 3. What You Must Escalate - Journalist / MP / known campaigner → also notify CEO - s.40 (personal data) → copy DPO immediately - Commercial/procurement sensitivity → copy CFO - Legal proceedings risk → FOI Lead for legal advice - Vexatious pattern → FOI Lead before proceeding - s.36 (prejudice to public affairs) → qualified person opinion required from Chair/CEO
The 10-section structure
| # | Section | What it contains |
|---|---|---|
| 1 | Identity & Purpose | Who the agent is, what organisation it serves, what its core function is |
| 2 | Autonomous Actions | Everything the agent can do without asking — the list should be exhaustive |
| 3 | Escalation Rules | What must be routed to a human, who to escalate to, how fast, in what format |
| 4 | Key Workflows | Step-by-step process for each main task (FOI receipt, EIR receipt, SAR redirect, etc.) |
| 5 | Communication Style | Tone and format for different audiences (external requesters, FOI Lead, DPO) |
| 6 | External Stakeholders | ICO, NHS England, provider trusts — with purpose and expected response times |
| 7 | Internal Routing | Which other agents or humans receive which categories of case |
| 8 | Legal & Policy Framework | FOIA 2000, EIR, UK GDPR, NHS policies — the agent's legal operating context |
| 9 | Hard Prohibitions | What the agent must never do — the absolute limits |
| 10 | Performance Metrics | What success looks like, measured monthly — keeps the agent accountable |
4The Knowledge Base
The agent's knowledge base is three Markdown files. They are loaded into the Claude API prompt when analysing requests. Together, they give Claude enough context to answer approximately 80% of common FOI requests accurately without needing to search external systems.
How the knowledge base powers the agent
icb-profile.md is the primary reference. It contains structured facts about NHS Westshire ICB: the annual commissioning budget (£1.12 billion), the five major provider contracts, staff headcount (387 WTE), sickness absence rate (4.2%), property leases, IT systems, board composition, published policies, and pay band information. This is the document Claude searches when a requester asks "how many staff do you employ?" or "what is your budget?"
foi-disclosure-log.md contains 25 previous FOI responses in structured format. Each entry has a case reference, date, question, response type, and the actual response content. When a new request arrives, Claude checks this log for similar previous requests — enabling it to refer the requester to a previous response (saving time) and ensuring responses are consistent over time.
foi-exemptions-reference.md is the legal reference guide. It covers all main FOIA 2000 exemptions relevant to an NHS ICB — s.21 through s.43 — explaining when each applies, the public interest test considerations, and NHS-specific examples. It also covers EIR exceptions and when EIR applies instead of FOIA. Claude uses this to identify applicable exemptions and draft public interest test arguments.
Request: "Please provide the sickness absence rate for NHS Westshire ICB staff."
Claude's process: (1) Searches icb-profile.md → finds "Sickness absence rate: 4.2% (NHS average: 5.7%)". (2) Searches foi-disclosure-log.md → finds FOI-2024-0005 with the same question and a full response. (3) Checks foi-exemptions-reference.md → no exemption applies. (4) Decision: DISCLOSE, referring to the previous response for completeness.
Time from email receipt to draft ready: under 3 minutes.
Extending the knowledge base
The knowledge base is designed to grow. As the FOI Lead approves responses and adds them to the disclosure log, the agent gets better at recognising and answering similar questions. The ICB profile should be reviewed quarterly and updated whenever significant facts change (budget, staff numbers, contracts). The exemptions reference is stable and rarely needs updating unless legislation changes.
5The N8N Workflow
The email workflow contains 15 nodes. The form workflow contains 7. Both are importable directly into any N8N v1.x instance. Here is what each node does:
| Node | Type | Function |
|---|---|---|
| Schedule Trigger | scheduleTrigger |
Runs every 2 minutes; starts the pipeline |
| Read IMAP | emailReadImap |
Fetches UNSEEN emails from FOI inbox; marks as read |
| IF: New Emails? | if |
Stops execution if inbox is empty; continues if new email found |
| Code: Extract Email | code |
Parses sender/subject/body; generates FOI-YYYY-NNNN; calculates 20-working-day deadline |
| Code: Build API Payload | code |
Assembles Anthropic API request with system prompt (with cache_control) and user message |
| HTTP Request: Claude — Classify | httpRequest |
POST to Anthropic API; returns classification JSON (type, exemptions, escalation flag) |
| Code: Parse Classification | code |
Extracts JSON from Claude response; handles fallback if parsing fails |
| Switch: Route by Type | switch |
Routes to FOI / EIR / SAR / GENERAL paths based on classification |
| Code: Build Disclosure Analysis Payload | code |
Assembles second API call with full knowledge base context; requests disclosure decision and full draft |
| HTTP Request: Claude — Analyse | httpRequest |
Second Claude API call; returns disclosure decision, exemptions, full draft ACK and response |
| Code: Parse Draft Response | code |
Extracts structured analysis from Claude response; handles fallback |
| Send Acknowledgement | sendEmail |
Sends acknowledgement to requester via NHS.net SMTP |
| Send to Reviewer | sendEmail |
Sends full case alert with draft to FOI Lead inbox |
| Code: Prepare Log Entry | code |
Formats case data as array for Google Sheets append |
| Google Sheets: Log Case | googleSheets |
Appends new row to FOI Case Register |
The dual API call pattern
The email workflow makes two Claude API calls per request. This is a deliberate design choice. The first call is fast and lightweight — it classifies the request and checks for escalation triggers. If the request is from a journalist or MP, the workflow can immediately flag this before committing to a full analysis. The second call is more expensive (4,000 token output limit vs 1,000) and receives the full knowledge base context. Separating these two calls makes the workflow more efficient and easier to debug.
6IMAP Email Integration
The IMAP connection is what ties the agent to the real world. Without it, the workflow has no input. Here are the key settings for the three environments NHS organisations are most likely to use:
| Provider | IMAP Host | Port | SSL | Authentication |
|---|---|---|---|---|
| Gmail | imap.gmail.com |
993 | SSL/TLS | App Password (requires 2FA enabled) |
| Microsoft 365 / NHS.net | outlook.office365.com |
993 | SSL/TLS | OAuth2 recommended; App Password if available |
| Generic IMAP | your server | 993 | SSL/TLS | Username + password |
IMAP setup in 5 steps (NHS.net)
foi@westshire.icb.nhs.uk) rather than an individual user account. In Microsoft 365 admin, create the shared mailbox and grant the N8N service account access to it.IMAP.AccessAsUser.All and SMTP.Send. Generate a client secret.outlook.office365.com, Port: 993, SSL/TLS. Connect via OAuth2 using your Azure app credentials.Security considerations for NHS deployment
Never use an individual employee's NHS.net credentials for the IMAP connection. Use a shared mailbox with access granted to a service account. This means the connection does not break when staff leave, can be centrally managed, and has its own audit trail. Review the setup with your Microsoft 365 admin and IG team before connecting to the live FOI inbox.
7Data Sovereignty
When the FOI Agent processes a request, the email content is sent to Anthropic's API for reasoning. This means data crosses out of your NHS infrastructure to US-based servers. This is the central compliance question for NHS deployment.
The second article in this series set out a three-approach framework for NHS organisations handling data sovereignty:
- Approach A (On-premise models): Data never leaves NHS infrastructure; AI reasoning runs locally. Highest sovereignty; significant infrastructure cost; model quality may be lower.
- Approach B (API with contractual controls): Data sent to external AI via signed Data Processing Agreement and Standard Contractual Clauses. No training on your data. GDPR-compliant transfer mechanism.
- Approach C (UK-region cloud AI): Data processed on UK-region infrastructure (e.g. Azure OpenAI UK South). Data stays in UK; model is provided by Microsoft/OpenAI rather than Anthropic.
For FOI requests, Approach B is defensible for most NHS organisations. Here is why:
| FOI Data Type | Typical Classification | Data Sovereignty Approach |
|---|---|---|
| Standard FOI request (e.g. "how many staff do you employ?") | OFFICIAL | Approach B — contractual |
| FOI request containing requester's contact details | OFFICIAL | Approach B — personal data covered by DPA |
| FOI request that names a specific ICB employee and asks for their information | OFFICIAL — triggers s.40 | Consider pseudonymising the name before API call |
| FOI request that inadvertently contains patient data | OFFICIAL-SENSITIVE | Do not send to external API — escalate to DPO |
| Request that appears to be a Subject Access Request | OFFICIAL — redirect to SAR process | Route to DPO — do not process through FOI pipeline |
FOI requests occasionally contain patient-identifiable information — for example, a requester describing a specific clinical incident involving themselves or a family member. The current workflow does not automatically screen for this. Before going live, discuss with your DPO whether you need a pre-processing step to check for patient data before the API call. For the majority of FOI requests (staff numbers, budgets, contracts, governance) this is not a concern.
Anthropic's Data Processing Agreement is available at anthropic.com/legal/data-processing-agreement. It confirms that API inputs are not used to train models and provides GDPR-compliant Standard Contractual Clauses for UK-to-US transfers. Ensure your organisation has signed this DPA before using the API in production.
8Going Live — NHS Compliance
Before activating the agent on the live FOI inbox, work through this 10-item pre-deployment checklist with your FOI Lead, DPO, and digital team:
-
Anthropic DPA signed and in place — confirm with your procurement or IG team that the Anthropic Data Processing Agreement has been signed by an authorised signatory. IG requirement
-
DPIA completed — a Data Protection Impact Assessment is required before deploying any AI system that processes personal data. Even for FOI (where personal data is limited), a DPIA scoping exercise should be completed and signed off by the DPO. UK GDPR Art.35
-
FOI Policy updated — update the ICB's FOI Policy to note that AI-assisted drafting is used in the FOI process. Responses are still reviewed and approved by the FOI Lead. Transparency is required. ICO guidance
-
FOI Lead trained on the internal alert format — the FOI Lead must understand how to read Claude's draft response, how to identify cases that need significant editing, and how to use the escalation flags. Operational requirement
-
Escalation contacts confirmed — verify that the email addresses for Diane Okafor (FOI Lead), Andrew Kellaway (DPO), Michael Chen (CFO), and Sarah Thornton (CEO) are correct in the .env file. Governance requirement
-
N8N instance secured with HTTPS and authentication — the N8N instance must not be accessible without authentication. Use N8N basic auth (or better: SSO/SAML) and ensure HTTPS is configured. Cyber Essentials requirement
-
N8N encryption key backed up securely — the
N8N_ENCRYPTION_KEYencrypts stored credentials. If this is lost, credentials must be re-entered. Back it up to your organisation's secrets management system. IT security requirement -
Regression test checklist complete — all 10 items in the testing guide (Guide 04) must pass before go-live. Get sign-off from the FOI Lead on at least 5 test case outputs. Quality assurance
-
Day-15 reminder logic tested — the FOIA 2000 s.10 20-working-day deadline is a legal requirement. Verify that the workflow correctly calculates the deadline and generates Day-15 reminders. Miss this and you risk ICO complaints. FOIA 2000 s.10
-
Monitoring and alerting set up — configure N8N error notifications so that if the workflow fails (e.g. API key expires, IMAP connection drops), the system administrator is alerted immediately. An undetected failure means FOI requests are not processed and deadlines may be missed. Operational resilience
FOIA 2000 obligations the agent must meet
The agent is designed specifically to meet these statutory obligations:
s.10 — Time for compliance: The 20-working-day deadline is calculated automatically, with exactness (skipping weekends and UK bank holidays). Day-10, Day-15, and Day-18 reminders are sent automatically to prevent deadline drift.
s.17 — Refusal notices: When Claude recommends refusal under an exemption, the draft response includes a properly structured s.17 refusal notice: the exemption cited, whether it is absolute or qualified, the public interest test (for qualified exemptions), and the requester's internal review and ICO complaint rights.
The agent cannot guarantee these obligations are met — the FOI Lead must review and approve every response. But it ensures that the raw material for compliance is prepared correctly and on time.
9Example Exchange
Here is a complete example, from email received to draft response, showing the full pipeline in action.
The FOI Lead (Diane Okafor) receives this alert, reviews the draft, makes any edits, and sends the approved response. Total elapsed time from email receipt to draft ready in her inbox: under 5 minutes. The draft is well-structured, cites the correct legislation, includes a public interest test argument, and includes the statutory appeal rights. She may approve it as-is or make adjustments — but the substantive work is done.
10What to Do Next
Adapting for your NHS organisation
The three knowledge base files are the only things that need to change to deploy this for a different NHS organisation. Replace:
knowledge-base/icb-profile.md— replace all NHS Westshire ICB facts with your organisation's data. Budget, staff numbers, contracts, board members, properties, published policies.knowledge-base/foi-disclosure-log.md— populate with your organisation's actual disclosure log. If you have a disclosure log on your website already, this is largely a reformatting exercise.agents/foi-agent.mdYAML header — update with your ICB name, email domain, and the names of your FOI Lead, DPO, CFO, and CEO.
The N8N workflows, the exemptions reference, and all the guides are generic and do not need to change.
Adding more agents to the network
The FOI Agent is one node in a larger network. The full NHS Managed Agents architecture described in the companion articles includes 24 agents covering complaints, commissioning contracts, finance support, PALS, digital systems, workforce, and more. Each follows the same 10-section agent definition structure. Each plugs into the same N8N orchestration layer.
Once the FOI Agent is running, adding the next agent (for example, the Complaints Agent) requires: writing its .md agent definition file; building any relevant knowledge base; creating its N8N workflow. The infrastructure — N8N, Claude API, Google Sheets — is already in place.
Scaling beyond FOI
The patterns demonstrated here — structured agent definition, separate knowledge base, dual API call (classify then analyse), human approval before sending — are general. They apply to any administrative process where:
- Requests arrive at a known inbox and follow predictable patterns
- There is a structured body of knowledge the agent can search
- Statutory or policy rules define when to disclose and when to escalate
- A human professional must review and approve before anything is sent
NHS complaints handling, SAR processing, and primary care commissioning queries all fit this pattern. The FOI Agent is the proof of concept. The architecture scales.
This is not a system that replaces the FOI Lead. It is a system that means Diane Okafor spends her time on judgment — the public interest test, the commercially sensitive contract, the journalist who needs careful handling — rather than on case registration, deadline calculation, and acknowledgement drafting. The agent handles the 70% of a FOI caseload that is routine administration. The FOI Lead handles the 30% that requires professional expertise. That is a good use of both.