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.

Repository

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:

📧
1. Receive the request
N8N polls 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.
n8n-nodes-base.emailReadImap / formTrigger
🏷️
2. Generate case reference and calculate deadline
A case reference is generated in the format 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.
n8n-nodes-base.code — JavaScript
🧠
3. Classify the request (Claude API Call 1)
The first Claude API call classifies the request: FOI, EIR, SAR, GENERAL, or UNCLEAR. It identifies the subject matter, potential exemptions, whether escalation is required, and whether the requester appears to be a journalist or MP. Response is structured JSON.
claude-sonnet-4-6 · max_tokens: 1000
📚
4. Analyse and draft response (Claude API Call 2)
The second call receives the full knowledge base context — the ICB profile, disclosure log, and exemptions reference — and produces a complete disclosure analysis: what information is held, which exemptions apply, a draft acknowledgement to the requester, and a full draft response for the FOI Lead to review.
claude-sonnet-4-6 · max_tokens: 4000 · prompt caching
✉️
5. Send acknowledgement to requester
An acknowledgement email is sent automatically to the requester within minutes of receipt. It includes the case reference, the exact deadline date, and the ICB's sign-off. This meets the ICB's 2-hour acknowledgement target.
n8n-nodes-base.sendEmail · NHS.net SMTP
🔔
6. Alert FOI Lead with full draft
An internal alert is sent to Diane Okafor (FOI Lead) containing the full case details, Claude's classification, the draft response, any escalation flags, and notes on applicable exemptions. The FOI Lead reviews, edits if needed, and approves before sending.
n8n-nodes-base.sendEmail · FOI Lead inbox
📊
7. Log to case register
Every case is appended to the FOI Case Register in Google Sheets: case reference, date, requester, subject, type, deadline, draft decision, escalation flag, and status. This provides the audit trail and pipeline visibility.
n8n-nodes-base.googleSheets
FOI Agent — Full Execution Flow
EMAIL Requester WEB FORM ICB Website N8N RECEIVES IMAP / Webhook CLAUDE #1 Classify DATA SOVEREIGNTY BOUNDARY CLAUDE #2 Analyse + Draft DECISION ACK / Draft / Escalate ACK email → Requester Alert + Draft → FOI Lead Google Sheets FOI Case Register

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: FOI-YYYY-NNNN
- 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

Escalation format: [FOI ESCALATION] prefix;
structured summary with deadline, reason,
preliminary assessment, recommended action
YAML Header
Structured metadata enables routing, reporting, and version control. The supervising_human field defines who owns this agent — the one person whose approval is required for every final output.
Section 2 — Autonomous Actions
Every action listed here the agent performs without asking. The 20-working-day calculation, the case reference generation, the acknowledgement send — all happen automatically. The draft response is prepared autonomously but sent only after FOI Lead approval.
Section 3 — Escalation Rules
This is the governance heart of the agent. Journalists, MPs, personal data, commercial sensitivity, legal risk — all trigger immediate escalation to named individuals. The agent stops processing and hands off.
Sections 4-10
Detailed workflows (4), communication style (5), external stakeholders (6), internal routing (7), legal framework (8), hard prohibitions (9), and performance metrics (10). The agent reads all of this on every API call.

The 10-section structure

#SectionWhat it contains
1Identity & PurposeWho the agent is, what organisation it serves, what its core function is
2Autonomous ActionsEverything the agent can do without asking — the list should be exhaustive
3Escalation RulesWhat must be routed to a human, who to escalate to, how fast, in what format
4Key WorkflowsStep-by-step process for each main task (FOI receipt, EIR receipt, SAR redirect, etc.)
5Communication StyleTone and format for different audiences (external requesters, FOI Lead, DPO)
6External StakeholdersICO, NHS England, provider trusts — with purpose and expected response times
7Internal RoutingWhich other agents or humans receive which categories of case
8Legal & Policy FrameworkFOIA 2000, EIR, UK GDPR, NHS policies — the agent's legal operating context
9Hard ProhibitionsWhat the agent must never do — the absolute limits
10Performance MetricsWhat 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.

Example: knowledge base in action

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)

1
Create a shared mailbox for the FOI address
Use a shared mailbox (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.
2
Register an Azure AD application for OAuth2
In Azure Portal → App registrations → create app with redirect URI pointing to your N8N instance. Grant permission: IMAP.AccessAsUser.All and SMTP.Send. Generate a client secret.
3
Create the IMAP credential in N8N
Settings → Credentials → Add Credential → IMAP. Name it exactly "FOI IMAP Account". Host: outlook.office365.com, Port: 993, SSL/TLS. Connect via OAuth2 using your Azure app credentials.
4
Test the credential
Use N8N's "Test Credential" button. A green tick means the connection is working. If it fails: check the Azure app permissions are admin-consented and the client secret has not expired.
5
Send a test email and verify processing
Send a test FOI request to the FOI inbox. Wait up to 2 minutes. Check N8N executions — you should see the workflow fire, the IMAP node pick up the email, and the full pipeline run through to the Google Sheets log.

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:

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
The one important caveat

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:

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.

STEP 1 Incoming FOI Request — received 14 May 2026, 10:14am
From: marcus.baines@westshire-watch.org.uk To: foi@westshire.icb.nhs.uk Subject: FOI Request - agency staff spending Dear FOI Officer, Under the Freedom of Information Act 2000, I am requesting the following information from NHS Westshire ICB: 1. The total amount spent on agency and temporary staff in 2024/25. 2. A breakdown of this spend by staff category (e.g. administrative, clinical, IT, communications). 3. The names of the agencies used and the value of contracts with each. I look forward to your response. Marcus Baines Westshire Watch (local accountability group)
STEP 2 N8N Processes — 4 minutes later, 10:18am
Case Reference: FOI-2026-3847 Deadline: Wednesday, 11 June 2026 (20 working days) Classification (Claude Call 1): { "request_type": "FOI", "classification_confidence": "HIGH", "summary": "Request for total agency/temp staff spend in 2024/25, breakdown by category, and names of agencies used with contract values.", "subject_matter": "agency and temporary staff expenditure", "potential_exemptions": ["s.43"], "escalation_required": false, "requester_type": "MEMBER_OF_PUBLIC", "likely_held_by_icb": true } Disclosure Analysis (Claude Call 2): { "disclosure_decision": "PARTIAL", "information_held": "ICB holds total agency spend figures and category breakdown. Individual agency names and contract values may be subject to s.43 review...", "exemptions_applied": [ { "section": "s.43", "description": "Commercial interests", "type": "QUALIFIED" } ] }
STEP 3 Acknowledgement Sent Automatically — 10:18am
From: foi@westshire.icb.nhs.uk To: marcus.baines@westshire-watch.org.uk Subject: Your FOI request — Case Reference FOI-2026-3847 — NHS Westshire ICB Dear Mr Baines, Thank you for your Freedom of Information request received on Wednesday, 14 May 2026. Your request has been logged with case reference FOI-2026-3847. We will respond to your request by Wednesday, 11 June 2026, as required by Section 10 of the Freedom of Information Act 2000. If you have any queries, please contact us at foi@westshire.icb.nhs.uk quoting your case reference FOI-2026-3847. Freedom of Information Team NHS Westshire Integrated Care Board Westshire House, 12 Cathedral Quarter Westminster-upon-Avon WS1 2AB foi@westshire.icb.nhs.uk | www.westshireicb.nhs.uk
STEP 4 Internal Alert to FOI Lead — 10:18am (for Diane Okafor's review)
[FOI CASE ALERT] FOI-2026-3847 — FOI: agency staff expenditure — Deadline: 11 June 2026 Case Reference: FOI-2026-3847 Date Received: Wednesday, 14 May 2026 Statutory Deadline: Wednesday, 11 June 2026 Request Type: FOI | Draft Decision: PARTIAL FROM: Marcus Baines <marcus.baines@westshire-watch.org.uk> Westshire Watch (local accountability group) CLASSIFICATION: Agency and temporary staff spend 2024/25 ESCALATION REQUIRED: No POTENTIAL EXEMPTIONS: s.43 (commercial interests — agency names/contract values) INTERNAL NOTES: Points 1 and 2 (total spend and category breakdown) can be disclosed from our published financial data. Point 3 (agency names and contract values) requires s.43 assessment — recommend CFO input on whether individual agency names/values are commercially sensitive. Similar to FOI-2024-0003. Consider referring to spend transparency pages for contracts above £25k. ------- DRAFT RESPONSE (for your review and approval) ------- Dear Mr Baines, Thank you for your Freedom of Information request dated 14 May 2026 (case reference FOI-2026-3847). NHS Westshire ICB can provide the following information: 1. TOTAL AGENCY AND TEMPORARY STAFF SPEND 2024/25 NHS Westshire ICB spent £2,847,000 on agency and temporary staff in the financial year 2024/25 (provisional; final audited figures will be published in the Annual Report in July 2026). 2. BREAKDOWN BY CATEGORY Administrative and corporate functions: £1,100,000 Communications and engagement: £384,000 Finance and contracting: £329,000 Digital and IT: £612,000 Other/programme management: £422,000 3. AGENCY NAMES AND CONTRACT VALUES Some information is withheld under Section 43(2) of the Freedom of Information Act 2000 (commercial interests). The ICB has determined that disclosure of individual agency names and contract values would or would be likely to prejudice the commercial interests of those agencies and of the ICB in future procurement exercises. Public interest test: The ICB has considered whether the public interest in disclosure outweighs the public interest in maintaining this exemption. While there is a legitimate public interest in transparency of public expenditure, the ICB has determined that the commercial interest in protecting supplier pricing and competitive position outweighs this in this instance. The ICB uses NHS Professionals and NHS Employers-approved framework agreements for the majority of agency spend. All contracts above £25,000 are published on Contracts Finder and on the ICB's spend transparency pages. YOUR RIGHT TO AN INTERNAL REVIEW If you are dissatisfied with this response, you may request an internal review within 40 working days of this response. Please write to: Diane Okafor, Head of Corporate Affairs NHS Westshire ICB foi@westshire.icb.nhs.uk If you remain dissatisfied following an internal review, you have the right to complain to the Information Commissioner's Office: ico.org.uk/concerns. Yours sincerely, Freedom of Information Team NHS Westshire Integrated Care Board

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:

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:

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.

A realistic assessment

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.