mcp-freeagent
mcp-freeagent is a self-hosted Model Context Protocol (MCP) server for FreeAgent, the UK accounting software. It lets MCP clients such as claude.ai, Claude Desktop and Claude Code read a company’s books and keep them: contacts, projects and time, invoices, estimates and credit notes, bills, expenses and mileage, bank transactions and their explanations, reports, tax returns and payroll.
| Endpoint | What it does |
|---|---|
/freeagent | 86 tools and 14 prompts for the books of the company whose FreeAgent user signed in |
/mcp | Every enabled service’s tools and prompts in one connector, named <service>_<tool>, for example freeagent_list_invoices. See Connecting clients |
Highlights
- People sign in with FreeAgent itself. The server sends each person to FreeAgent to log in and approve its app, and keeps the refresh token FreeAgent grants only in encrypted form inside that person’s own MCP tokens. There are no API keys to paste, and every call acts as that FreeAgent user, within their access level. See Signing in with FreeAgent.
- Read and write. Lists and reports, plus tools that create and change records: raise and send invoices, explain bank transactions, approve FreeAgent’s guesses, record bills and expenses, log time, post journals.
api_getandapi_requestreach every other FreeAgent endpoint. - Prompts as slash commands. 14 ready-made jobs, such as monthly bookkeeping, explaining bank transactions and chasing overdue invoices. The Claude Code plugin adds them as
/freeagent:...commands. - Safe by default. Write tools are annotated so clients ask before running them, and the prompts show what will change and wait for agreement.
FREEAGENT_READ_ONLY=freeagenthides and refuses every write tool. Every write is recorded in an audit log that never contains arguments or results. - A single static Rust binary, also shipped as a
FROM scratchcontainer image (ghcr.io/trozz/mcp-freeagent). TLS end to end, a built-in OAuth 2.1 server for claude.ai custom connectors, and no database.
mcp-freeagent is built on mcp-server-core, the same base as mcp-icloud, mcp-companies-house and mcp-twenty-crm.
How it talks to FreeAgent
The server uses the FreeAgent API v2 and FreeAgent’s own OAuth:
| Purpose | Address |
|---|---|
| The live API | https://api.freeagent.com/v2 |
The sandbox API (FREEAGENT_ENVIRONMENT=sandbox) | https://api.sandbox.freeagent.com/v2 |
| Approving the app (in the person’s browser) | approve_app below the API base |
| Exchanging and refreshing tokens | token_endpoint below the API base |
Every request names the server in its User-Agent, as FreeAgent requires, and FreeAgent’s rate limits apply per user: 120 requests a minute and 3600 an hour.
What it does not do
- File returns with HMRC. FreeAgent files VAT, corporation tax and self assessment returns from its own interface.
mark_tax_returnonly records that a return was filed or paid elsewhere. - Read the bank’s live balance. Bank balances are FreeAgent’s, built from explained transactions.
- Run payroll.
get_payrollreads pay periods, payments and payslips; it changes nothing. - Act beyond the signed-in user. FreeAgent refuses anything above that user’s access level, and the tool says so.
Privacy
The server keeps no copy of the books. Logs record tool names, outcomes and durations, never the content of invoices, contacts or transactions, unless you explicitly turn on unsafe content logging while debugging. See Security.
Next: Getting started.
Getting started
This page takes you from nothing to a running server. You need a FreeAgent login (or a FreeAgent sandbox company to try it on), and a machine that can run Docker or a single binary.
1. Create a FreeAgent app
Each person signs in through FreeAgent’s own OAuth, under an app you register once.
- Open the FreeAgent Developer Dashboard and create an app.
- Note its OAuth identifier and OAuth secret. They become
FREEAGENT_CLIENT_IDandFREEAGENT_CLIENT_SECRET. - Add the redirect URI
<PUBLIC_URL>/callback, for examplehttps://freeagent-mcp.example.com/callback. For local use, addhttp://localhost:7771/callback. FreeAgent matches redirect URIs exactly, port included.
Signing in with FreeAgent explains what happens with the app during a sign-in.
2. Choose a secret for the server
The server needs one secret of its own besides the app secret:
OAUTH_SIGNING_KEY: at least 32 bytes, used to sign the server’s OAuth tokens and to encrypt the FreeAgent refresh token inside them. Generate one withopenssl rand -hex 32and keep it stable: changing it signs everyone out.
There is no admin password and no static token. OAUTH_ADMIN_PASSWORD is not read, and setting MCP_AUTH_TOKEN stops the server at startup, because everyone signs in with their own FreeAgent account.
Store the secrets in a secret manager or an environment file readable only by you. Every variable can also be read from a file: append _FILE to its name, for example FREEAGENT_CLIENT_SECRET_FILE=/run/secrets/freeagent_secret.
3. Run it
Locally, to try it
Plain HTTP on localhost is enough for Claude Code on the same machine, because the sign-in happens in your own browser. With the redirect URI http://localhost:7771/callback registered:
export FREEAGENT_CLIENT_ID=your-oauth-identifier
export FREEAGENT_CLIENT_SECRET=your-oauth-secret
PUBLIC_URL=http://localhost:7771 BIND_ADDR=127.0.0.1:7771 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) LOG_FORMAT=pretty \
./mcp-freeagent
From a clone of the repository, cargo run -p mcp-freeagent instead of ./mcp-freeagent does the same. Add FREEAGENT_ENVIRONMENT=sandbox to use a sandbox company instead of real books. Then connect Claude Code.
With Docker
mkdir -p data && sudo chown 65532:65532 data
docker run -d --name mcp-freeagent -p 8443:8443 \
-e PUBLIC_URL=https://freeagent-mcp.example.com \
-e OAUTH_SIGNING_KEY="$(openssl rand -hex 32)" \
-e FREEAGENT_CLIENT_ID=your-oauth-identifier \
-e FREEAGENT_CLIENT_SECRET=your-oauth-secret \
-e FREEAGENT_TOKEN_STORE=/data/tokens.json \
-v "$PWD/data:/data" \
ghcr.io/trozz/mcp-freeagent:latest
PUBLIC_URL is the address clients and FreeAgent use to reach the server. See TLS and public access for how to make it reachable with a trusted certificate. FREEAGENT_TOKEN_STORE keeps sign-ins working across restarts; see Tokens. The server runs as UID 65532, so the directory must be writable by it.
With Docker Compose and a Cloudflare tunnel
A tunnel gives the server a public HTTPS address with a trusted certificate, without opening a port on your network. Create a tunnel in the Cloudflare dashboard, add a public hostname such as freeagent-mcp.example.com pointing to https://mcp-freeagent:8443 with No TLS Verify turned on (the server’s own certificate is self-signed in this setup), and copy the tunnel token.
compose.yaml:
services:
mcp-freeagent:
image: ghcr.io/trozz/mcp-freeagent:latest
container_name: mcp-freeagent
restart: unless-stopped
env_file: app.env
ports:
- "127.0.0.1:8443:8443"
volumes:
- ./data:/data
- ./audit:/audit
tunnel:
image: cloudflare/cloudflared:latest
restart: unless-stopped
command: tunnel --no-autoupdate run
environment:
TUNNEL_TOKEN: ${TUNNEL_TOKEN}
depends_on:
- mcp-freeagent
app.env (readable only by you, for example chmod 600 app.env):
PUBLIC_URL=https://freeagent-mcp.example.com
OAUTH_SIGNING_KEY=replace-with-the-output-of-openssl-rand-hex-32
FREEAGENT_CLIENT_ID=your-oauth-identifier
FREEAGENT_CLIENT_SECRET=your-oauth-secret
FREEAGENT_TOKEN_STORE=/data/tokens.json
AUDIT_LOG_PATH=/audit/audit.jsonl
The server runs as UID 65532, so both directories must be writable by it: mkdir -p data audit && sudo chown 65532:65532 data audit. Then start both containers with TUNNEL_TOKEN=<token> docker compose up -d, and register https://freeagent-mcp.example.com/callback with the FreeAgent app.
With the binary
Download the archive for your platform from Releases (Linux x86_64 and arm64, macOS arm64), verify the checksum, extract it and run:
shasum -a 256 -c mcp-freeagent-<version>-<target>.tar.gz.sha256
tar -xzf mcp-freeagent-<version>-<target>.tar.gz
cd mcp-freeagent-<version>-<target>
PUBLIC_URL=https://freeagent-mcp.example.com OAUTH_SIGNING_KEY=... \
FREEAGENT_CLIENT_ID=... FREEAGENT_CLIENT_SECRET=... \
./mcp-freeagent
All configuration comes from environment variables; the configuration reference lists every one.
4. Check it is running
curl -k https://127.0.0.1:8443/healthz
prints ok (use http:// with INSECURE_HTTP=true). The startup log has a freeagent settings line with the API address and the app’s client id, a service enabled line with the service’s URL and tools, and a combined endpoint enabled line for /mcp.
mcp-freeagent --version prints the version, and mcp-freeagent --healthcheck exits 0 when the local server answers /healthz (the container image uses it as its HEALTHCHECK).
5. Choose what runs
FREEAGENT_READ_ONLY=freeagent(orall) hides and refuses every write tool. Reports, lists andapi_getkeep working. See Security.FREEAGENT_COMBINED=falseturns off the combined/mcpendpoint.FREEAGENT_SERVICESselects services. There is one,freeagent, so it only matters for keeping configuration explicit.
Next: Signing in with FreeAgent.
Signing in with FreeAgent
There are no API keys and no shared password. Each person who connects a client signs in with their own FreeAgent login, and every tool call then acts as that FreeAgent user, within their access level.
The FreeAgent app
The server reaches FreeAgent as one OAuth app, registered in the FreeAgent Developer Dashboard:
FREEAGENT_CLIENT_IDis the app’s OAuth identifier (8 to 128 letters, digits,-and_).FREEAGENT_CLIENT_SECRETis its OAuth secret. FreeAgent lets an app have two secrets at once, so a leaked secret can be replaced without downtime.- Its redirect URI must be exactly
<PUBLIC_URL>/callback, port included, for examplehttps://freeagent-mcp.example.com/callbackorhttp://localhost:7771/callback. Register one per address you run the server at.
The path /callback is reserved for FreeAgent’s redirect.
FREEAGENT_ENVIRONMENT=sandbox points the server at FreeAgent’s sandbox (https://api.sandbox.freeagent.com/v2) instead of the live API.
A sign-in, step by step
sequenceDiagram
participant C as MCP client
participant S as mcp-freeagent
participant U as You (browser)
participant F as FreeAgent
C->>S: POST /freeagent (no token)
S-->>C: 401, WWW-Authenticate: resource_metadata=.../oauth-protected-resource/freeagent
C->>S: discovery and POST /register
C->>U: open /authorize (PKCE S256, resource=.../freeagent)
U->>S: approve the client on the consent page
S-->>U: encrypted cookie, redirect to FreeAgent approve_app
U->>F: log in and approve the app
F-->>U: redirect to /callback with a code
U->>S: GET /callback (code, state, cookie)
S->>F: POST token_endpoint (code)
F-->>S: access token (1 hour) and refresh token
S->>F: GET users/me and company (who signed in)
S-->>C: authorization code (redirect)
C->>S: POST /token (code + verifier)
S-->>C: MCP access token (1 hour) and refresh token (30 days), FreeAgent refresh token sealed inside
- Consent.
GET /authorizeshows which MCP client is asking (its self-reported name, marked unverified) and where you will be sent back to. The server asks here for every client, because all of them reach FreeAgent under this server’s one app, so FreeAgent’s own approval screen cannot tell them apart. - To FreeAgent. The button to continue to FreeAgent sets a cookie holding the pending request, encrypted under a key derived from
OAUTH_SIGNING_KEYand bound to a randomstate. It isHttpOnly,SameSite=Lax, limited to/callback,Secureover https, and lasts 10 minutes. Your browser goes to FreeAgent’sapprove_apppage. - Back. FreeAgent sends the browser to
<PUBLIC_URL>/callback. The server checksstateagainst the cookie, so FreeAgent’s code is only accepted from the browser that started the sign-in, and exchanges the code at FreeAgent’stoken_endpoint. - Who you are. The server reads
users/meandcompanyto name you asfreeagent:<company subdomain>:user:<user id>(orfreeagent:user:<user id>when the subdomain is not available). That name is the subject in logs and the audit log, and stays the same across sign-ins. - To the client. The browser returns to the client with an authorization code, which the client exchanges at
/tokenfor its MCP tokens.
If you decline at FreeAgent, the client receives access_denied. If FreeAgent refuses the code, the page says why, and the attempt counts towards the sign-in limits.
Tokens
FreeAgent grants an access token (valid for an hour) and a refresh token. The refresh token is the person’s credential:
- It is sealed into their MCP tokens with ChaCha20-Poly1305, under a key derived from
OAUTH_SIGNING_KEY. Anyone holding an MCP token can read its claims, but not the sealed refresh token. - On each tool call the server opens it and turns it into a FreeAgent access token. Access tokens are kept only in memory, per person, and refreshed 2 minutes before FreeAgent says they expire, one refresh at a time per person.
- If FreeAgent refuses an access token early, the server refreshes it once and sends the request again.
Rotating refresh tokens and the token store
FreeAgent may hand out a new refresh token on each refresh, and does not say whether the old one keeps working. The server always uses the newest one. The sealed token inside the client’s MCP tokens never changes, so the newest one has to be remembered elsewhere:
- Without
FREEAGENT_TOKEN_STORE, it is remembered in memory only. A restart forgets it, and people whose refresh token was replaced must sign in again. - With
FREEAGENT_TOKEN_STORE, the newest refresh token of each sign-in is also written to that file, so restarts lose nothing.
The file is safe to keep on a volume:
- Each entry is encrypted with ChaCha20-Poly1305 under a key derived (HKDF-SHA256) from that sign-in’s original refresh token, which only that person’s MCP tokens carry, and is indexed by a hash of it. The file alone gives nothing away, even with
OAUTH_SIGNING_KEY. - It is created on the first write with mode 0600, together with its directory, and written atomically (a temporary file beside it, then a rename).
- Entries not updated for 100 days are dropped when the server starts. A sign-in that FreeAgent refuses is removed.
- A file that exists but cannot be read, or is not a token store, stops the server at startup. A failed write is logged (
writing the FreeAgent token store failed) and counted infreeagent_token_store_errors_total; the tool call still succeeds.
Run one replica, or send each person to the same replica (sticky sessions), each with its own file. Two replicas sharing one file would overwrite each other’s entries.
Client authentication at FreeAgent
FreeAgent documents HTTP Basic authentication for the app’s credentials, and the server uses it. If FreeAgent refuses them that way, the server tries once with them in the request body, keeps doing so if that works, and logs a warning naming the variables to check.
Access levels
Tools can do only what the signed-in FreeAgent user can do. get_current_user reports their permission_level:
| Level | Access |
|---|---|
| 0 | None |
| 1 | Time |
| 2 | My money |
| 3 | Contacts and projects |
| 4 | Invoices, estimates and files |
| 5 | Bills |
| 6 | Banking |
| 7 | Tax, accounting and users |
| 8 | Full |
A call above the user’s level fails with a permission: error that says so; see Working with the tools.
What ends a sign-in
| Event | Effect | What the person does |
|---|---|---|
| The MCP access token is an hour old | 401 on the endpoint | Nothing: the client refreshes |
| The client has not refreshed for 30 days | Its refresh token has expired | Signs in again |
| 90 days since sign-in | Every grant lasts at most 90 days | Signs in again |
| FreeAgent no longer accepts the refresh token (revoked, expired, replaced and lost, or access to the app withdrawn) | Tools fail with auth: FreeAgent no longer accepts this connection's sign-in ... | Reconnects the connector, or runs /mcp in Claude Code |
FREEAGENT_ENVIRONMENT, FREEAGENT_API_URL or FREEAGENT_CLIENT_ID changes | Every grant ends | Signs in again |
OAUTH_SIGNING_KEY or PUBLIC_URL changes | Every token and client registration stops working | Removes the connector and adds it again |
Changing FREEAGENT_CLIENT_SECRET ends nothing. Restarts end nothing either, as long as FREEAGENT_TOKEN_STORE keeps any replaced refresh tokens.
The OAuth server itself is mcp-server-core’s, using its upstream sign-in; its documentation covers every token and endpoint in detail.
Next: Connecting clients.
Connecting clients
The FreeAgent tools are at /freeagent, and /mcp offers every enabled service together. Add one connector, for either:
| Endpoint | Connector URL | Tool names |
|---|---|---|
| FreeAgent | https://freeagent-mcp.example.com/freeagent | list_invoices |
| All services | https://freeagent-mcp.example.com/mcp | freeagent_list_invoices |
Use one or the other, not both: with both, every tool appears twice.
Every client signs in through FreeAgent with OAuth. There is no static token, and a client cannot send a FreeAgent token as its bearer token instead.
claude.ai, Claude Desktop and Claude mobile
These connect from Anthropic’s servers, so the server must be reachable from the internet with a publicly trusted certificate (see TLS and public access).
- In claude.ai open Settings, then Connectors, then Add custom connector.
- Enter the connector URL, for example
https://freeagent-mcp.example.com/freeagent. - The server’s consent page opens and names the client. Continue to FreeAgent, log in, and approve the app.
The connector then signs in with OAuth on its own. Its access tokens last one hour and its refresh tokens 30 days, and the client refreshes them itself; after 90 days you sign in again. Connectors added in claude.ai are also available in Claude Desktop and the Claude mobile apps.
Claude Code
claude mcp add --transport http freeagent https://freeagent-mcp.example.com/freeagent
Then run /mcp in Claude Code, choose freeagent and authenticate. Your browser shows the server’s consent page, then FreeAgent’s login. For a server on your own machine, use http://localhost:7771/freeagent (see Getting started).
The Claude Code plugin sets up the same connection and adds the prompts as slash commands.
Other MCP clients
Any client that speaks the MCP Streamable HTTP transport and completes the OAuth flow (dynamic client registration, authorization code with PKCE) works. A request without a token gets a 401 whose WWW-Authenticate header points to /.well-known/oauth-protected-resource/freeagent (or /mcp), where discovery starts. The client must open the authorization URL in a browser, since the person signs in at FreeAgent.
The combined endpoint
/mcp serves every enabled service’s tools and prompts as <service>_<name>. mcp-freeagent has one service, so /mcp offers the same 86 tools and 14 prompts as /freeagent, prefixed freeagent_, and the prompts’ text names the prefixed tools.
- It is its own OAuth protected resource, with metadata at
/.well-known/oauth-protected-resource/mcp. A token issued for/mcpworks only there, and a token for/freeagentdoes not work on/mcp. FREEAGENT_READ_ONLYapplies there too: the write tools are hidden and refused.- Audit lines name the real service and tool, with
"endpoint": "/mcp". FREEAGENT_COMBINED=falseturns it off;/mcpthen returns 404.
/freeagent keeps tool names short. /mcp is useful when you want the freeagent_ prefix to tell these tools apart from other connectors’ tools of the same name.
Icons
The endpoint sends its own icon in serverInfo, and /favicon.ico serves the project icon. Some clients, including claude.ai at the time of writing, show a generic icon for custom connectors regardless.
Configuration reference
Everything is configured with environment variables. The server checks all of them at startup and refuses to start with a list of every problem it found, so a typo never leaves it half configured.
General rules:
- An empty value counts as unset.
- Every variable can also be read from a file by appending
_FILEto its name, for exampleFREEAGENT_CLIENT_SECRET_FILE=/run/secrets/freeagent_secret. A value set directly wins over the file, and a trailing newline in the file is ignored. Use this for secrets with Docker or Kubernetes secrets. - Booleans accept
true,false,1,0,yes,no,onandoff. - Lists are comma separated; spaces around names are ignored.
Server and HTTP
| Variable | Required | Default | Example | Description |
|---|---|---|---|---|
PUBLIC_URL | yes | https://freeagent-mcp.example.com | External base URL clients and FreeAgent use, without a path. Must be https; http is accepted only for localhost, 127.0.0.1 or [::1]. FreeAgent’s redirect URI is this plus /callback | |
BIND_ADDR | no | 0.0.0.0:8443 | 127.0.0.1:7771 | Listen address, an IP address and port. It must accept loopback connections (0.0.0.0 does) so --healthcheck can reach 127.0.0.1 |
TLS_CERT_PATH, TLS_KEY_PATH | no | /certs/fullchain.pem, /certs/privkey.pem | PEM certificate chain and private key. Both or neither; reloaded automatically when the files change. See TLS and public access | |
INSECURE_HTTP | no | false | true | Serve plain HTTP. For local use, or when TLS is terminated in front of the server on a network you trust |
ALLOWED_ORIGINS | no | http://localhost:6274 | Extra browser Origin values accepted on MCP requests, comma separated. The PUBLIC_URL origin is always allowed | |
TRUSTED_PROXIES | no | 10.0.0.2,10.0.0.3 | Proxy IP addresses whose X-Forwarded-For is trusted for sign-in rate limiting |
Sign-in and tokens
| Variable | Required | Default | Example | Description |
|---|---|---|---|---|
OAUTH_SIGNING_KEY | yes | output of openssl rand -hex 32 | Key that signs the server’s OAuth tokens and encrypts the FreeAgent refresh token inside them, at least 32 bytes. Changing it signs everyone out | |
FREEAGENT_CLIENT_ID | yes | abcd1234EFGH5678 | The FreeAgent app’s OAuth identifier: 8 to 128 letters, digits, - and _. Changing it signs everyone out | |
FREEAGENT_CLIENT_SECRET | yes | the app’s OAuth secret | The FreeAgent app’s OAuth secret | |
FREEAGENT_TOKEN_STORE | no | /data/tokens.json | File that keeps each sign-in’s newest refresh token, encrypted, across restarts. See Tokens |
OAUTH_ADMIN_PASSWORD is not read: people sign in with FreeAgent instead. MCP_AUTH_TOKEN must not be set; the server refuses to start with it, because every request needs a FreeAgent sign-in.
FreeAgent
| Variable | Required | Default | Example | Description |
|---|---|---|---|---|
FREEAGENT_ENVIRONMENT | no | production | sandbox | production (or live) for the live API, sandbox for FreeAgent’s sandbox. Anything else stops startup. Changing it signs everyone out |
FREEAGENT_API_URL | no | from FREEAGENT_ENVIRONMENT | http://127.0.0.1:9999/v2 | The API base, ending /v2. Must be https, or http to a loopback address (for tests); no credentials, query or fragment. Overrides FREEAGENT_ENVIRONMENT. Changing it signs everyone out |
FREEAGENT_API_VERSION | no | 2026-09-01 | An X-Api-Version date to send with every API request, as YYYY-MM-DD |
Services
| Variable | Required | Default | Example | Description |
|---|---|---|---|---|
FREEAGENT_SERVICES | no | all (freeagent) | freeagent | Services to run. There is one, freeagent. An unknown name or an empty list stops startup |
FREEAGENT_READ_ONLY | no | none | freeagent or all | Services whose write tools are hidden and refused, on their own endpoint and under /mcp. An unknown name stops startup. See Security |
FREEAGENT_COMBINED | no | true | false | Serve the combined endpoint /mcp. With false, /mcp returns 404 |
Logging, metrics and audit
| Variable | Required | Default | Example | Description |
|---|---|---|---|---|
LOG_LEVEL | no | info | info,mcp_freeagent=debug | Log filter in tracing syntax. Targets: mcp_freeagent (which covers mcp_freeagent_books) and mcp_server_core. The audit target always stays on at info |
LOG_FORMAT | no | json | pretty | json or pretty |
DEBUG | no | false | true | Debug logging: each FreeAgent request’s method, path, status and duration, retries, token requests, and tool error messages (which can quote ids and values from the books). Never response bodies, tool results or credentials |
DEBUG_UNSAFE_LOG_CONTENT | no | false | true | Also logs full tool results and FreeAgent response bodies, which puts the company’s books in the logs. A warning is printed at startup. Credentials are never logged |
METRICS_ADDR | no | 0.0.0.0:9090 | Starts a separate plain-HTTP Prometheus listener. Keep it on an internal network. See Operations | |
OTEL_EXPORTER_OTLP_ENDPOINT | no | http://otel-collector:4318 | Exports traces over OTLP/HTTP. The standard OTEL_EXPORTER_OTLP_HEADERS is honoured. Nothing is exported unless it is set | |
AUDIT_LOG_PATH | no | /audit/audit.jsonl | File every write tool call is appended to as one JSON line (created with mode 0600). Audit lines are always logged too. See Security |
The server variables (everything not starting with FREEAGENT_) come from mcp-server-core; its configuration reference gives every rule in full.
A complete example
PUBLIC_URL=https://freeagent-mcp.example.com
OAUTH_SIGNING_KEY_FILE=/run/secrets/oauth_signing_key
FREEAGENT_CLIENT_ID=your-oauth-identifier
FREEAGENT_CLIENT_SECRET_FILE=/run/secrets/freeagent_secret
FREEAGENT_TOKEN_STORE=/data/tokens.json
FREEAGENT_READ_ONLY=freeagent
AUDIT_LOG_PATH=/audit/audit.jsonl
LOG_FORMAT=json
TLS and public access
claude.ai connects to your server from Anthropic’s infrastructure, so for claude.ai the server must be reachable from the internet over HTTPS with a publicly trusted certificate. Claude Code and other clients on your own machine can use plain HTTP on localhost, or a certificate you trust yourself.
The person signing in also needs to reach the server from their browser: FreeAgent sends the browser back to <PUBLIC_URL>/callback.
How the server picks its certificate
At startup, in this order:
INSECURE_HTTP=true: plain HTTP, no TLS. Use it on your own machine, or when TLS is terminated in front of the server on a network you trust.TLS_CERT_PATHandTLS_KEY_PATHboth set: the server loads them, and reloads them automatically when the files change (for example after a certificate renewal). If either file is missing or invalid the server refuses to start; it never falls back silently. Setting only one of them is an error.- Neither set: the server generates an in-memory self-signed certificate for the
PUBLIC_URLhost,localhost,127.0.0.1and::1. It is never written to disk, changes on every restart, and its SHA-256 fingerprint is logged.
The self-signed certificate is fine for encrypting the hop from a tunnel or reverse proxy that skips verification. It does not work for claude.ai directly, and a browser warns about it on the sign-in pages.
Local use
The simplest setup for Claude Code on the same machine is plain HTTP on loopback:
PUBLIC_URL=http://localhost:7771 BIND_ADDR=127.0.0.1:7771 INSECURE_HTTP=true ./mcp-freeagent
PUBLIC_URL may be http only for localhost, 127.0.0.1 or [::1]. Register http://localhost:7771/callback as the FreeAgent app’s redirect URI. See Getting started for the other variables.
Option A: a Cloudflare tunnel
The simplest way to get a trusted public address. The tunnel’s edge certificate is trusted by claude.ai and browsers, and the server’s self-signed certificate protects the hop from the tunnel to the server. See the Docker Compose example in Getting started. In the tunnel’s public hostname settings, point the service to https://mcp-freeagent:8443 and turn on No TLS Verify.
Set PUBLIC_URL to the tunnel hostname, for example https://freeagent-mcp.example.com.
Option B: a reverse proxy
Run the server behind nginx, Caddy or Traefik with a trusted certificate at the proxy:
- Proxy to
https://<server>:8443(verification off, or pinned to the logged fingerprint), or setINSECURE_HTTP=trueif the proxy and server share a trusted network. - Pass the
Hostheader through unchanged and do not buffer responses (MCP uses streaming HTTP responses). - Set
TRUSTED_PROXIESto the proxy’s IP address so the server uses the client address fromX-Forwarded-Forfor sign-in rate limiting. - Requests to the server are limited to 1 MiB; set the proxy’s limit to the same, for example nginx’s
client_max_body_size 1m.
Option C: the server holds the certificate
Give the server a certificate from Let’s Encrypt or another public CA:
docker run -d --name mcp-freeagent -p 443:8443 \
-v /etc/letsencrypt/live/freeagent-mcp.example.com:/certs:ro \
-e TLS_CERT_PATH=/certs/fullchain.pem \
-e TLS_KEY_PATH=/certs/privkey.pem \
--env-file app.env \
ghcr.io/trozz/mcp-freeagent:latest
Renewals are picked up without a restart. With certificate files, the server also sends Strict-Transport-Security.
A trusted local certificate
For HTTPS on your own machine, for example to test the same PUBLIC_URL scheme you deploy with.
With mkcert:
brew install mkcert
mkcert -install
mkcert -cert-file cert.pem -key-file key.pem localhost 127.0.0.1 ::1
TLS_CERT_PATH=$PWD/cert.pem TLS_KEY_PATH=$PWD/key.pem ./mcp-freeagent
With openssl:
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 825 \
-keyout key.pem -out cert.pem -subj "/CN=freeagent-mcp.example.com" \
-addext "subjectAltName=DNS:freeagent-mcp.example.com,DNS:localhost,IP:127.0.0.1"
Add cert.pem to the trust store of the machine running the client and the browser, or to NODE_EXTRA_CA_CERTS for Node based clients.
Working with the tools
Endpoint /freeagent (or freeagent_<tool> under /mcp). The 79 tools cover one company’s books: the company of the FreeAgent user who signed in.
| Area | Tools | Page |
|---|---|---|
| Company | 5 | Company and contacts |
| Contacts and notes | 7 | Company and contacts |
| Projects and tasks | 7 | Projects and time |
| Timeslips and timers | 6 | Projects and time |
| Invoices, estimates, credit notes | 18 | Sales |
| Bills, expenses and mileage | 11 | Purchases |
| Bank accounts, transactions and explanations | 11 | Banking |
| Categories, reports, journals, tax returns, payroll | 12 | Accounting and tax |
| Any other FreeAgent endpoint | 2 | Any other endpoint |
A good start in a conversation is get_company (company type, VAT status, accounting year) and business_snapshot (balances, money owed, unexplained transactions, deadlines).
Reads and writes
Every tool tells the client what it does, through MCP annotations:
- read:
readOnlyHint. Lists, reports andapi_get. Never audited, and still available on a read-only server. - write: creates, changes or sends something. Clients usually ask before running these, and every call is audited.
- write, destructive: also
destructiveHint, for deletes and other changes that are hard to undo: everydelete_*,invoice_action,mark_tax_returnandapi_request.
The server’s instructions and every prompt tell the model to show the person what will be created, changed, sent or deleted, and wait for their agreement first.
Arguments
- Ids. Every resource has an id. Tools take it as the id itself (
123, or750-1for a sub-account) or as the FreeAgent URL a tool returned (https://api.freeagent.com/v2/contacts/2). Results carry anidbeside everyurl. Never guess an id: find it with alist_or search tool first. - Money is a decimal string with at most two decimals, such as
"1250.00", in the company’s currency unless a currency is given. Commas and the symbols£,$and€are removed. Quantities, rates and percentages take up to four decimals. - Dates are
YYYY-MM-DD.from_datemust not be afterto_date. - Signs follow FreeAgent. Bank money out is negative and money in positive. An expense’s
gross_valueis negative when it is owed to the claimant, butcreate_expenseandupdate_expensetake what was spent as a positiveamount. - Categories are nominal codes such as
285or001.list_categoriesfinds them by words. - Text fields are limited to 2000 characters.
- Lists of items (invoice and bill lines, journal entries, timeslips, statement lines) hold at most 100.
extraon many create and update tools passes any other field by FreeAgent’s own name, for fields the tool does not name.- Attachments (receipts, supplier invoices) go in as base64 in
data_base64, with afile_nameand optionally acontent_type(application/pdf,image/png,image/jpegorimage/gif, otherwise guessed from the file name). Requests to the server are limited to 1 MiB in all, so files over about 700 KB are refused.
Lists and paging
List tools take page (1 to 10000, default 1) and per_page (1 to 100, default 25). The answer is:
{"count": 25, "total": 140, "page": 1, "next_page": 2, "items": [...]}
next_page is present only when there is a next page; pass it as page for more. Answers are compact JSON: FreeAgent’s envelopes are unwrapped, and empty values (nulls, empty strings, empty lists) are dropped. false and 0 are kept. Some fields are left out of every answer:
- Signed download links on attachments and the company logo (
content_src, its thumbnails andexpires_at). An expense’s receipt keeps its id, file name, type, size and description. The links expire 30 seconds after FreeAgent issues them and are about 2,000 characters each. locked_attributes, the field-by-field list of what is locked on an item in a locked accounting period.is_lockedandlocked_reasonstay.ni_numberandunique_tax_reference: people’s National Insurance numbers and tax references.
A page of a list that would come to more than 50,000 characters (about 17,000 tokens), more than clients reliably accept in a tool result, is refused with a too_large error that says which per_page fits.
Errors
A failed tool call returns a tool error (isError: true) whose text starts with a kind:
| Kind | Meaning |
|---|---|
auth | FreeAgent no longer accepts this connection’s sign-in (revoked, expired or replaced). Sign in again: reconnect the connector, or run /mcp in Claude Code |
permission | FreeAgent refused (HTTP 403): the signed-in user’s access level does not allow it, or the feature does not apply to this company |
not_found | Nothing at that id or path |
rate_limited | FreeAgent’s limit of 120 requests a minute and 3600 an hour per user is used up. The message says how long to wait |
validation | An argument is wrong, or FreeAgent rejected the request (HTTP 400, 406, 409 or 422); the message says which |
upstream | FreeAgent could not be reached, timed out or answered unexpectedly; usually temporary |
internal | A problem inside the server, such as FreeAgent refusing the server’s own app credentials; check the log |
read_only | The service is read-only on this server (FREEAGENT_READ_ONLY) |
too_large | A page of a list is too long for a tool result; ask again with the per_page the message gives |
Retries and timeouts
- Reads are retried once, after a short pause, following a network error or a 5xx answer.
- Writes are never retried once they reach FreeAgent, so a slow create cannot run twice.
- If FreeAgent refuses the access token (HTTP 401), the server refreshes it and sends the request once more. This is safe for writes, since FreeAgent refused the request before acting on it.
- Requests time out after 30 seconds (10 seconds to connect). Redirects are never followed.
Company and contacts
Who the books belong to, who is signed in, and the customers and suppliers in them. Conventions for ids, money, paging and errors are on Working with the tools.
Company
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
get_company | read | The company these books belong to: name, type (limited company, sole trader and so on), currency, accounting year dates, VAT registration and rates, address and registration number. Call it first for context | none |
get_current_user | read | The signed-in FreeAgent user: name, email, role and permission_level (see Access levels). National Insurance numbers and tax references are left out of this and every result | none |
list_users | read | The company’s FreeAgent users (directors, employees, accountants) with their ids, roles and permission levels. Needs the tax, accounting and users access level | view: all (default), staff, active_staff, advisors or active_advisors |
get_tax_timeline | read | Upcoming and recent deadlines for VAT returns, corporation tax, self assessment, payroll and Companies House filings, with amounts due where known | none |
business_snapshot | read | Where the business stands, in one call: company basics, each bank account’s balance, number of unexplained transactions and explanations to approve, money owed to you (open and overdue invoices) and by you (open and overdue bills), and the next tax deadlines | none |
business_snapshot
- It sums up to 500 open invoices and 500 open bills; when there are more, that section is marked
truncated. - Each visible bank account shows
unexplained_transactionsandexplanations_to_approve(FreeAgent’s guesses awaiting approval), as FreeAgent counts them. Hidden accounts are left out. - A section it cannot read, for example because the user’s access level does not cover banking, is listed under
unavailablewith the error, and the rest is still returned. - Bank balances are FreeAgent’s, from explained transactions, not the bank’s live balance.
Contacts and notes
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
search_contacts | read | Find customers and suppliers. With query, every word must appear in the name, organisation or email; without it, lists a page. Each result has its id, name, email and account_balance | query, view, sort, updated_since, page, per_page |
get_contact | read | One contact in full: names, emails, phones, address, payment terms, VAT settings, account_balance and active projects count | id |
create_contact | write | Create a customer or supplier. Give organisation_name, or first_name and last_name. Search first so you do not create a duplicate | contact fields (below) |
update_contact | write | Change only the fields given. status Hidden hides it from lists | id, contact fields, status (Active or Hidden) |
delete_contact | write, destructive | Delete a contact. FreeAgent refuses when it has invoices, bills or projects: hide it with update_contact instead | id |
list_notes | read | The notes on one contact or project, newest first, with author and dates | contact_id or project_id |
create_note | write | Add a note to a contact or project, for example a record of a call or a payment promise | note, and contact_id or project_id |
Searching contacts
FreeAgent has no contact search of its own, so with a query the tool reads up to 3000 contacts and matches every word locally, ignoring case. When there are more, it says only the first 3000 were searched; narrow with view or updated_since.
view:all,active(default),clients,suppliers,active_projects,completed_projects,open_clients,open_suppliersorhidden.sort:name(default),created_atorupdated_at; prefix-for newest first, such as-updated_at.updated_since:YYYY-MM-DDor an ISO 8601 date-time.
Contact fields
organisation_name, first_name, last_name, email, billing_email (where invoices are emailed, when not email), phone_number, mobile, address1, address2, address3, town, region, postcode, country (as FreeAgent spells it, such as United Kingdom), default_payment_terms_in_days, charge_sales_tax (Auto (default), Always or Never), sales_tax_registration_number (their VAT number) and extra for any other field by FreeAgent’s name, such as {"locale": "fr", "contact_name_on_invoices": true}.
Projects and time
Projects for clients, the tasks time is logged against, and the timeslips themselves. Conventions for ids, money, paging and errors are on Working with the tools.
Projects and tasks
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_projects | read | Projects with their client (contact), status, budget, billing rate and currency | contact_id, view: active (default), completed, cancelled or hidden; page, per_page |
get_project | read | One project in full: client, status, budget, billing rate, dates and currency | id |
create_project | write | Create a project for a client. status defaults to Active, budget_units to Hours and currency to the company’s | contact_id, name, project fields (below) |
update_project | write | Change only the fields given. Set status Completed to close it | id, project fields |
list_tasks | read | Tasks, optionally for one project, with billing rate and whether they are billable | project_id, view: all (default), active, completed or hidden; updated_since, page, per_page |
create_task | write | Create a task on a project, such as Development or Meetings, so time can be logged against it | project_id, name, billing_rate, billing_period (hour or day), is_billable (default true), status |
update_task | write | Change only the fields given | id, name, billing_rate, billing_period, is_billable, status (Active, Completed or Hidden) |
Project fields
name, status (Active, Completed, Cancelled or Hidden), budget and budget_units (Hours, Days or Monetary: what the budget counts), normal_billing_rate (the default rate for its tasks, such as 450) with billing_period (hour or day), hours_per_day (for day rates, such as 7.5), currency (ISO 4217, such as GBP), starts_on, ends_on, contract_po_reference, and extra for any other field by FreeAgent’s name, such as {"is_ir35": true}.
Timeslips and timers
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_timeslips | read | Logged time with date, hours, comment, task, project and user, and whether each is billed. view unbilled shows time not yet invoiced; running shows live timers | view: all (default), unbilled or running; project_id, task_id, user_id, from_date, to_date, updated_since, nested, page, per_page |
log_time | write | Create one or more timeslips. The user defaults to the signed-in user and the project to the task’s own. Returns the timeslips created | entries (1 to 100, below) |
update_timeslip | write | Change a timeslip’s hours, date, comment or task. Billed timeslips cannot be changed | id, hours, dated_on, comment, task_id |
delete_timeslip | write, destructive | Delete a timeslip | id |
start_timer | write | Start the timer on a timeslip. To time new work, create one with log_time and hours 0 first. Only one timer runs at a time | id |
stop_timer | write | Stop the timer; the timeslip’s hours then include the time timed | id |
nested: true on list_timeslips includes each timeslip’s user, project and task in full.
Timeslip entries
Each entry of log_time’s entries:
| Field | Required | Meaning |
|---|---|---|
task_id | yes | The task worked on (list_tasks) |
dated_on | yes | The day, YYYY-MM-DD |
hours | yes | Hours as a decimal: 1h30 is 1.5. 0 with start_timer to time it live |
comment | no | |
project_id | no | Default: the task’s own project |
user_id | no | Who did the work. Default: the signed-in user |
Unbilled time becomes an invoice with create_invoice and include_timeslips; see Sales.
Sales
Invoices, estimates and credit notes, and sending them. Conventions for ids, money, paging and errors are on Working with the tools.
Invoices
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_invoices | read | Invoices with reference, contact, dates, status (Draft, Open, Overdue, Paid and so on), total_value and due_value | view, contact_id, project_id, sort, updated_since, with_items, page, per_page |
get_invoice | read | One invoice in full, with its line items, totals, VAT, what is paid and due, and its payment link | id |
create_invoice | write | Create a draft invoice from line items, a project’s unbilled time and expenses, or both. Returns it with its id and totals | contact_id, items, invoice fields (below) |
update_invoice | write | Change only the fields given. items adds lines; an item with id changes that line, and with id and delete: true removes it. Sent invoices may be locked: mark_as_draft first | id, invoice fields |
delete_invoice | write, destructive | Delete a draft invoice. Sent invoices are refused: cancel them with invoice_action mark_as_cancelled, or issue a credit note | id |
invoice_action | write, destructive | Move an invoice through its life (below) | id, action |
list_recurring_invoices | read | Recurring invoice profiles FreeAgent invoices from on a schedule, with frequency, next_recurs_on and status | contact_id, view: draft, active or inactive (default all) |
list_invoices view: all (default), recent_open_or_overdue, open, overdue, open_or_overdue, draft, paid, scheduled_to_email, thank_you_emails, reminder_emails, or last_N_months such as last_3_months. open_or_overdue shows what customers owe. sort is created_at (default) or updated_at, prefixed - for newest first.
Invoice fields
| Field | Meaning |
|---|---|
contact_id | The customer. Required on create |
items | Line items (below), up to 100 |
dated_on | The invoice date. Default on create: today |
payment_terms_in_days | Days until due; 0 means due on receipt. Default on create: the contact’s payment terms, otherwise 30 |
due_on | A fixed due date instead of payment terms |
reference | Invoice number. Default: the next in sequence |
currency | ISO 4217 code. Default: the company’s currency |
comments | Text shown on the invoice, such as payment details or thanks |
discount_percent, po_reference, project_id | |
ec_status | UK/Non-EC (default), EC Goods, EC Services, Reverse Charge or EC VAT MOSS |
include_timeslips, include_expenses | A project’s unbilled time and rebillable expenses; see below. Need project_id |
extra | Any other invoice field by FreeAgent’s name, such as {"payment_methods": {"stripe": true}} |
An invoice stays a draft until invoice_action mark_as_sent or send_document_email.
Invoicing a project’s time and expenses
create_invoice with project_id adds:
include_timeslips: the project’s unbilled time, grouped asbilled_grouped_by_single_timeslip,billed_grouped_by_timeslip,billed_grouped_by_timeslip_taskorbilled_grouped_by_timeslip_date.include_expenses: its rebillable expenses, grouped asbilled_grouped_by_single_expenseorbilled_grouped_by_expense.
Invoice actions
invoice_action action:
| Action | Effect |
|---|---|
mark_as_sent | Marks it sent without emailing it. Also re-opens a cancelled invoice |
mark_as_draft | Back to draft, so it can be edited |
mark_as_scheduled | To be emailed by FreeAgent |
mark_as_cancelled | Writes off an unpaid invoice |
convert_to_credit_note | Makes it a draft negative invoice |
duplicate | A new draft copy dated today |
To email an invoice, use send_document_email. To record a payment, explain the bank transaction with paid_invoice_id (Banking).
Estimates
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_estimates | read | Estimates and quotes with reference, contact, status and totals | view: all (default), recent, draft, non_draft, sent, approved, rejected or invoiced; contact_id, project_id, from_date, to_date, updated_since, with_items, page, per_page |
get_estimate | read | One estimate or quote in full, with its items | id |
create_estimate | write | Create a draft estimate, quote or proposal from line items | contact_id, reference (such as EST-012), items, estimate_type (Estimate (default), Quote or Proposal), dated_on (default today), currency, discount_percent, ec_status, notes, project_id, extra |
estimate_action | write | mark_as_sent, mark_as_draft, mark_as_approved, mark_as_rejected, convert_to_invoice (makes a draft invoice from it) or duplicate | id, action |
Credit notes
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_credit_notes | read | Credit notes with reference, contact, status and values | view: all (default), recent_open_or_overdue, open, overdue, open_or_overdue, draft, refunded or last_N_months; contact_id, project_id, updated_since, page, per_page |
get_credit_note | read | One credit note in full, with its items | id |
create_credit_note | write | A draft credit note for a customer, for example to credit part of an invoice. Prices are positive | contact_id, items, dated_on (default today), payment_terms_in_days (default 0), reference, currency, comments, project_id, extra |
Apply a credit note to an invoice or refund it in FreeAgent, or with api_request on credit_note_reconciliations (Any other endpoint).
Line items
Each item of items on invoices, estimates and credit notes:
| Field | Meaning |
|---|---|
description | What was sold, as it reads on the document. Required for a new item |
quantity | How many, such as 7.5. Default for a new item: 1 |
price | Price per unit before VAT, such as 80 |
item_type | Hours, Days, Weeks, Months, Years, Products, Services, Training, Expenses, Comment, Bills, Discount, Credit, VAT or Stock; leave out for no unit |
category | Income category as a nominal code, such as 001 (Sales). Default: the company’s sales category |
sales_tax_rate | VAT percentage, such as 20, 5 or 0. Default: from the contact’s charge_sales_tax setting; on an estimate, the company’s standard rate, or 0 for a contact never charged VAT |
sales_tax_status | TAXABLE, EXEMPT or OUT_OF_SCOPE |
id, delete | On update: the id of an existing item to change, and delete: true to remove it. Leave id out to add an item. An existing item keeps every field the update does not give |
Sending and documents
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
send_document_email | write | Email an invoice, estimate or credit note to the customer through FreeAgent, with a link to view (and pay) it. A draft invoice is marked as sent | document (invoice, estimate or credit_note), id, subject and body, or use_template; to, from, email_to_sender |
get_document_pdf | read | The PDF of an invoice, estimate or credit note, as an embedded application/pdf resource, for example to attach or save | document, id |
list_email_addresses | read | The verified addresses FreeAgent can send from, for send_document_email’s from | none |
list_price_list_items | read | The price list: saved products and services with code, description, price, unit and VAT, to reuse as invoice lines | sort: created_at, code or updated_at; page, per_page |
send_document_email details:
tois comma-separated addresses. Default: the contact’s billing email, otherwise its main email.frommust be a verified address fromlist_email_addresses. Default: FreeAgent’s.use_template: truesends FreeAgent’s own email template instead ofsubjectandbody. FreeAgent adds the view and pay link either way.email_to_sendersends a copy to the sender. Default: true.
Purchases
Bills from suppliers, expenses people paid themselves, and mileage. Conventions for ids, money, paging and errors are on Working with the tools.
Which tool to use for a cost:
- A supplier’s invoice the company will pay: a bill (
create_bill). Pay it by explaining the bank transaction withpaid_bill_id. - Something a person paid personally and is owed back: an expense (
create_expense). - A cost paid from a company bank account or card: neither. Explain the bank transaction instead (Banking).
- Business mileage:
create_mileage_claim.
Bills
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_bills | read | Bills with reference, supplier, dates, status, total_value and due_value. view open_or_overdue shows what the company owes | view: all (default), open, overdue, open_or_overdue, paid, recurring, hire_purchase or cis; contact_id, project_id, from_date, to_date, updated_since, with_items, page, per_page |
get_bill | read | One bill in full, with its lines, VAT and what is paid and due | id |
create_bill | write | Record a bill: reference, date, lines with a category and total including VAT, and optionally the supplier’s invoice attached. Due 30 days after its date unless due_on is given | contact_id, reference, dated_on, due_on, items, attachment, currency, comments, ec_status, extra |
update_bill | write | Change only the fields given. items adds lines; an item with id changes that line, and with id and delete: true removes it | id, bill fields |
delete_bill | write, destructive | Delete a bill | id |
ec_status is UK/Non-EC (default), EC Goods, EC Services or Reverse Charge. extra takes any other bill field by FreeAgent’s name, such as {"recurring": "Monthly"}.
Bill lines
Each item of a bill’s items:
| Field | Meaning |
|---|---|
category | Expense category as a nominal code, such as 285 (Accommodation and Meals). Required |
total_value | The line’s total including VAT, such as 120.00 |
total_value_ex_tax | Or the line’s total before VAT |
description, quantity, project_id | |
unit | -no unit-, Hours, Days, Weeks, Months, Years, Products, Services, Training or Stock |
sales_tax_rate | VAT percentage, such as 20. Default: from the category |
sales_tax_status | TAXABLE, EXEMPT or OUT_OF_SCOPE |
manual_sales_tax_amount | An exact VAT amount, overriding the rate |
id, delete | On update: the line to change, and delete: true to remove it |
Expenses and mileage
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_expenses | read | Expense claims and mileage with user, category, date, description and gross_value (negative is money owed to the claimant) | view: recent or recurring (default all); project_id, from_date, to_date, updated_since, page, per_page |
get_expense | read | One expense or mileage claim in full: user, category, date, amounts, VAT, receipt and rebilling | id |
create_expense | write | Record an expense someone paid personally: category, date, description and the amount spent including VAT, optionally with the receipt | expense fields (below) |
create_mileage_claim | write | Claim business mileage at HMRC’s approved rates. FreeAgent works out the amount | dated_on, description, mileage, and the fields below |
update_expense | write | Change only the fields given. amount is what was spent, positive | id, expense fields |
delete_expense | write, destructive | Delete an expense | id |
Expense fields
| Field | Meaning |
|---|---|
amount | What was spent, including VAT, as a positive amount such as 42.50. The server stores it with FreeAgent’s sign |
refund | true when the claimant paid money back to the company instead |
category | Expense category as a nominal code, such as 285; see list_categories |
dated_on, description, receipt_reference | |
user_id | Who paid and is owed it. Default on create: the signed-in user |
currency | ISO 4217 code when not the company’s currency |
sales_tax_rate | VAT percentage. Default: from the category |
manual_sales_tax_amount | An exact reclaimable VAT amount, overriding the rate |
project_id, rebill_type | A project to rebill it to, and how: cost, markup or price |
attachment | The receipt |
extra | Any other expense field by FreeAgent’s name |
Mileage fields
| Field | Meaning |
|---|---|
dated_on, description | Required. The description says where and why, such as “Leeds to Manchester, client meeting” |
mileage | Required. Distance in the company’s mileage units (miles unless set to kilometres) |
vehicle_type | Car (default), Motorcycle or Bicycle |
engine_type | Petrol (default), Diesel, LPG, Electric, Electric (Home charger) or Electric (Public charger) |
engine_size | From FreeAgent’s mileage settings, such as “Up to 1400cc”; needed for VAT on fuel |
have_vat_receipt | Whether there is a VAT receipt for the fuel |
reclaim | Reclaim at the HMRC approved rate. Default: true; false only rebills it |
user_id | Who drove. Default: the signed-in user |
project_id |
Attachments
attachment on bills, expenses and bank explanations:
| Field | Meaning |
|---|---|
file_name | Required, such as receipt.pdf |
data_base64 | Required. The file, base64-encoded |
content_type | application/pdf, image/png, image/jpeg or image/gif. Default: from file_name |
description |
Requests to the server are limited to 1 MiB in all, so a file over about 700 KB is refused before it reaches FreeAgent.
Upload links
Models cannot pass a file shared in a chat to a tool, so for those, and for anything over about 700 KB, use an upload link. Made without a target, the link holds the file for 30 minutes so the model can read it, fill in the expense, bill or explanation from it, and attach it to what it made:
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
create_upload_link | write | A single-use link, valid for 30 minutes, where the person picks a PDF, PNG, JPEG or GIF of up to 5 MB. With target and id the server attaches it in FreeAgent as them; an expense or bill holds one file, and when it already has one, replaces names it, because the upload replaces it. Without them the file is held for the model | target (expense, bill or bank_transaction_explanation) and id, or neither |
get_upload_status | read | waiting (with the last error, if a try failed), uploading, received (held for the model) or attached | upload_url |
get_uploaded_file | read | The held file: a photo as an image the model can read, a PDF as an embedded file | upload_url |
get_attachment | read | A file already attached in FreeAgent, such as an expense’s receipt, by the attachment id the item shows. The server downloads it from FreeAgent’s signed storage link, which lasts 30 seconds, without sending a FreeAgent token | id |
attach_file | write | Attach a held file (upload_url), or one the client can read itself as base64 | target, id, and upload_url or file_name and data_base64; description |
Banking
Bank accounts, their transactions, and explaining what each transaction was. Conventions for ids, money, paging and errors are on Working with the tools.
Bank amounts follow FreeAgent: money out is negative and money in positive.
Accounts and transactions
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_bank_accounts | read | The company’s bank, credit card and PayPal accounts with id, name, type, currency and FreeAgent’s current_balance (from explained transactions, not the bank’s live balance) | view: standard_bank_accounts, credit_card_accounts or paypal_accounts (default all) |
get_bank_account | read | One bank account in full: type, currency, balance, account details and latest activity | id |
list_bank_transactions | read | One account’s transactions with date, amount, description, unexplained_amount and their explanations | bank_account_id, view, from_date, to_date, updated_since, last_uploaded, page, per_page |
get_bank_transaction | read | One bank transaction in full, with its explanations | id |
list_bank_feeds | read | Which accounts are connected to their bank, the feed state, and when its authorisation (SCA) expires and must be renewed in FreeAgent | none |
upload_bank_statement | write | Add transactions to an account from statement lines, for example for an account without a bank feed | bank_account_id, lines (1 to 100, below) |
list_bank_transactions view: all (default), unexplained (what still needs explaining), explained, manual, imported or marked_for_review (explained by FreeAgent’s guess, awaiting approval). last_uploaded: true shows only the transactions of the latest statement upload.
Statement lines
Each line of upload_bank_statement’s lines:
| Field | Meaning |
|---|---|
dated_on, description | Required |
amount | Required. Money out negative, money in positive |
fitid | The bank’s own transaction id, if known, so it is not imported twice |
transaction_type | CREDIT, DEBIT, INT, DIV, FEE, SRVCHG, DEP, ATM, POS, XFER, CHECK, PAYMENT, CASH, DIRECTDEP, DIRECTDEBIT, REPEATPMT or OTHER (default) |
Upload whole days: FreeAgent skips lines that match one already there by date, amount and description. Afterwards, list_bank_transactions with last_uploaded: true shows what was imported.
Explanations
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_bank_transaction_explanations | read | The explanations of one account’s transactions: what each payment or receipt was (category, invoice, bill, transfer or user), with VAT | bank_account_id, marked_for_review_only, from_date, to_date, updated_since, page, per_page |
explain_bank_transaction | write | Explain (categorise) a transaction: what the money was (below) | bank_transaction_id, and one of category, paid_invoice_id, paid_bill_id, transfer_bank_account_id or paid_user_id |
update_bank_transaction_explanation | write | Change only the fields given. marked_for_review: false approves one FreeAgent guessed | id, explanation fields, marked_for_review |
delete_bank_transaction_explanation | write, destructive | Delete an explanation, leaving the transaction unexplained again | id |
approve_explanations | write | Approve explanations FreeAgent guessed in one account (below) | bank_account_id, explanation_ids or approve_all, from_date, to_date |
Explaining a transaction
explain_bank_transaction takes the transaction (bank_transaction_id, from list_bank_transactions with view unexplained) and one way of saying what the money was:
| Field | The money was |
|---|---|
category | An ordinary payment or receipt, by nominal code such as 285 or 001; see list_categories |
paid_invoice_id | A customer paying an invoice (or a credit note refunded) |
paid_bill_id | Paying a supplier’s bill (or a bill refund) |
transfer_bank_account_id | Moved to or from another of the company’s own accounts |
paid_user_id | Paid to or received from a director or employee (expenses repaid, salary, director’s loan). Add category for a specific kind, such as 902 net salary |
Other fields: gross_value (the amount explained), dated_on, description, sales_tax_rate (default from the category), sales_tax_status (TAXABLE, EXEMPT or OUT_OF_SCOPE), ec_status (UK/Non-EC, EC Goods, EC Services, Reverse Charge or EC VAT MOSS), foreign_currency_value (for a foreign-currency invoice or bill, the amount in its currency), project_id and rebill_type (cost, markup or price), receipt_reference, attachment (see Attachments) and extra for any other explanation field, such as a stock item or capital asset.
gross_valueanddated_ondefault to the transaction’s unexplained amount and date.- An amount with the wrong sign, or more than is unexplained, is refused. So is a transaction that is already fully explained: change its explanation with
update_bank_transaction_explanationinstead. - A part explanation leaves the rest unexplained, to explain separately.
Approving FreeAgent’s guesses
FreeAgent guesses explanations for imported transactions and marks them for review. approve_explanations works on one account:
- With neither
explanation_idsnorapprove_all, it only lists the explanations awaiting approval (in the dates given) and changes nothing, so you can show them to the person. - With
explanation_ids, it approves those, up to 200; the dates are then not used. - With
approve_all: true, it approves every explanation awaiting approval in the account and dates, up to 200.
The result lists the ids approved and any that failed. update_bank_transaction_explanation with marked_for_review: false approves a single one.
Accounting and tax
The chart of accounts, reports, the general ledger and manual journals, tax returns and payroll. Conventions for ids, money, paging and errors are on Working with the tools.
Categories
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_categories | read | Find categories (the chart of accounts) by words in their name, code or tax reporting name. Their nominal_code is what bills, expenses, invoice lines and bank explanations take as category | query (such as travel, software or 285; leave out for all), group, sub_accounts |
group:income,cost_of_sales,admin_expensesorgeneral(the balance sheet). Default: all.sub_accounts: trueincludes sub-accounts such as each bank account (750-x) and each user (900-x).
Reports
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
get_profit_and_loss | read | Income, expenses, operating profit, deductions such as corporation tax and dividends, and retained profit. Default: the current accounting year to date | from_date, to_date, or accounting_period (a whole year, such as 2025/26) |
get_balance_sheet | read | Capital assets, current assets and liabilities, net current assets, total assets and owners’ equity at a date (FreeAgent rounds these to whole units) | as_at_date (default today) |
get_trial_balance | read | Every category with its total for a period. A non-zero 999 Suspense or large unexplained balances point at bookkeeping to finish | from_date, to_date (default today) |
get_cashflow | read | Cash in and out by month, from the bank accounts, with the closing balance. Historic only. Default: the last 12 months | from_date, to_date (default today) |
list_accounting_transactions | read | The general ledger: every posting for a period, optionally for one category, with debit_value (credit negative) and the item it came from | from_date, to_date, nominal_code (such as 285 or 750-1), page, per_page |
For get_trial_balance and get_cashflow, the period must be at most 12 months or within one accounting year.
Journals
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_journal_sets | read | Manual journals, optionally by tag | tag, from_date, to_date, page, per_page |
create_journal_set | write | Post a manual journal, such as a payroll journal or an accrual. Its entries must balance. Only for someone who knows double entry | dated_on, description, entries (2 to 100, below), tag |
Each entry of entries:
| Field | Meaning |
|---|---|
category | Required. The category’s nominal code, such as 401 or 814 |
debit_value | Required. Debit positive, credit negative, such as 2500.00 or -2500.00. The entries’ debit values must add up to zero |
description | |
user_id | For user categories (900 to 910): the user |
Journals are tagged mcp-freeagent unless another tag is given, so list_journal_sets with tag mcp-freeagent finds the ones posted through this server.
Tax returns
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
list_tax_returns | read | Tax returns of one kind with periods, filing due dates, filing status and payments due | kind, user_id |
get_tax_return | read | One return in full by its period end date. A VAT return includes its box 1 to 9 breakdown and payments | kind, period_ends_on (as list_tax_returns gives it), user_id |
mark_tax_return | write, destructive | Record that a return was filed or paid outside FreeAgent, or undo that: mark_as_filed, mark_as_unfiled, mark_as_paid or mark_as_unpaid. Needs full access | kind, period_ends_on, action, payment_date, user_id |
kindisvat,corporation_tax,self_assessmentorfinal_accounts.user_idapplies toself_assessmentonly. Default: the signed-in user.- Marking a VAT or self assessment payment needs
payment_date: the payment’s due date, as the return’s payments list it.
Nothing is filed with HMRC. FreeAgent files returns from its own interface; mark_tax_return only records what happened elsewhere. The vat_check prompt checks a VAT return before you file it in FreeAgent.
Payroll
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
get_payroll | read | Payroll for a tax year (UK, read only): its pay periods with filing status and the PAYE payments due; with period, that period’s payslips with pay, tax, NI, pensions and student loans | year, period |
yearis the tax year by the year it ends:2026for April 2025 to April 2026.periodis a pay period,0to11. Leave it out for the year’s periods and payments.
Reviews
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
month_end_check | read | What to finish before a month end or VAT return, with a to_do list: unexplained transactions and guesses to approve per bank account, expenses without receipts and the VAT they reclaim (mileage needs none), bills without the supplier’s invoice, draft invoices in the period or over 30 days old, overdue invoices and bills, the 999 Suspense balance and overdrawn directors’ loan accounts. Default period: the next VAT return’s, or last month for a company not registered for VAT | from_date and to_date, or neither |
director_loan_review | read | Each director’s loan account (positive: they owe the company), the expenses and salary the company owes them, and the net; the loan at the last year end, the s455 deadline nine months later, what was still owed then and the estimated s455 tax at 33.75%; a flag for loans over £10,000 (benefit in kind); and a set-off suggestion when expenses are owed to them. Figures are the balance sheet’s, to the nearest pound | as_at_date (default today) |
Any other endpoint
Two tools reach any part of the FreeAgent API the other tools do not cover, as the signed-in user. Prefer the specific tools when one fits: they fill in defaults, check arguments and shape the answers.
| Tool | Kind | What it does | Key parameters |
|---|---|---|---|
api_get | read | Read any endpoint, such as capital_assets, stock_items, hire_purchases, properties, account_locks, cis_bands, sales_tax_periods, credit_note_reconciliations, payroll_profiles/2026 or accounting/trial_balance/summary/opening_balances. Returns FreeAgent’s JSON with ids added | path, query |
api_request | write, destructive | Create, change or delete through any endpoint with POST, PUT or DELETE, with the body FreeAgent’s API documentation gives | method, path, query, body |
Because api_get is a read and api_request a write, a read-only server still allows the first and refuses the second.
Paths
pathis the endpoint below/v2, such asstock_items/12. A path starting/v2/, or a full URL on the configured FreeAgent API host, is accepted too.- Segments may hold letters, digits,
-,_and.;.and..on their own are refused, and so is a path over 200 characters. - A URL on any other host is refused, so the tools never send the person’s access token elsewhere.
- FreeAgent’s OAuth endpoints,
token_endpointandapprove_app, are refused. - Query parameters go in
query, never inpath.
Query and body
queryis an object of up to 20 parameters, such as{"view": "all", "page": "2"}. Names are lower-case letters, digits and_; values are strings, numbers or booleans.bodyis a JSON object, the one FreeAgent documents for the endpoint, with its root key, such as{"price_list_item": {...}}.
api_get answers {"body": ..., "total": ..., "has_next_page": true}, with total and has_next_page present when FreeAgent’s paging headers give them. api_request answers {"body": ...}, with location when FreeAgent names a created resource.
The FreeAgent API documentation lists every endpoint and its fields.
Prompts
Prompts are ready-made requests a client can offer you, often as slash commands. They tell the model which tools to call and in what order; they change nothing by themselves. The Claude Code plugin offers the same 14 as /freeagent:... commands.
| Prompt | Arguments | What it does |
|---|---|---|
business_snapshot | focus | A short briefing on where the business stands: cash in the bank, money owed to and by you, profit so far this year, and what needs attention, such as unexplained transactions, overdue invoices and the next tax deadlines. focus is anything you most want to know, such as “can I afford a £5,000 dividend?” |
monthly_bookkeeping | month (default last month) | Goes through one month: unexplained and unapproved bank transactions, draft and overdue invoices, unbilled time, unpaid bills and expenses, with a checklist of what to do and offers to fix each item |
explain_transactions | bank_account (default every account), period (default everything unexplained) | Suggests what each unexplained bank transaction was (the invoice it pays, a bill, a transfer, a director’s payment, or a category with VAT), says how sure it is, and explains them after you approve |
approve_guesses | bank_account (default every account) | Reviews the explanations FreeAgent guessed and marked for review, flags any that look wrong, and approves the rest once you agree |
chase_overdue | tone (friendly, firm or final; default friendly under 30 days overdue, firm after), customer | Lists overdue invoices by customer, oldest and largest first, drafts a reminder for each customer, sends the ones you approve through FreeAgent, and notes each chase on the contact |
create_invoice | request (required) | Raises an invoice from a plain description, such as “Acme, 3 days consulting at £600 a day, plus £45 train fare”: finds the customer, drafts the lines with VAT, and creates and sends it after you approve |
invoice_unbilled_time | client (default every client with unbilled time) | Finds unbilled time and rebillable expenses for a client or project and turns them into a draft invoice after you approve |
log_time | work (required) | Logs time from a plain description, such as “3h on the Acme website yesterday, 1.5h client call today”: matches projects and tasks and creates the timeslips after you approve |
record_expense | details (leave out to start from the receipt) | Records a receipt or supplier invoice: reads the receipt you send through an upload link, works out whether it is an out-of-pocket expense, a bill to pay or a bank payment to explain, picks the category and VAT, records it after you approve and attaches the receipt |
vat_check | period (default the next return due) | Checks a VAT return before you file it: the boxes, unexplained transactions and draft items in the period, unusual VAT treatments and the payment due, with a list of what to fix. It files nothing |
tax_deadlines | months (default 6) | Every upcoming tax and filing deadline (VAT, corporation tax, self assessment, payroll, Companies House) with amounts due, most urgent first, and anything overdue or unfiled |
month_end_close | month (default last month) | Checks a month is ready to close: every bank account explained, invoices and bills complete, the suspense account empty and the trial balance right, then reports what blocks closing |
director_loan_review | as_at (default today) | Each director’s loan account (what they owe or are owed, with expenses and salary owed to them), what makes it up, the s455 deadline and estimated tax on a loan still owed nine months after the year end, any benefit in kind over £10,000, and ways to clear it. It changes nothing |
cashflow_review | months (default 6) | Money in and out by month, what customers owe and when, bills and tax coming up, and how long the cash will last at the current rate |
How they behave
- Nothing changes without you. Every prompt that can write tells the model to show exactly what it will create, change, send or delete, usually as a table, and wait for your go-ahead; if you agree to only some of it, it does only that.
- Book text is data. Names, descriptions and bank references are written by customers, suppliers and banks; every prompt tells the model to ignore anything in them that reads like an instruction.
- Errors. Each prompt tells the model what to do with each error kind: stop and ask you to sign in again on
auth, carry on without the part your access level does not allow onpermission, stop and say how long to wait onrate_limited, and never guess another id onnot_found. - Read-only servers. Prompts stay listed when
FREEAGENT_READ_ONLYis set. A step that needs a hidden write tool tells the model to say so and skip that step. - Style. Answers are in plain British English, with money in the currency’s symbol and two decimals, and dates as
YYYY-MM-DD.
Arguments
- Arguments are text. A blank or missing optional argument takes its default; a missing required one is refused with what it should contain.
- Each argument is limited to 4000 characters, and an argument the prompt does not take is refused.
- Arguments are placed in the prompt inside their own tags, and a
<in them is replaced by a look-alike character, so an argument cannot break out of its place in the text.
On /mcp
Under the combined endpoint the prompts are named freeagent_<prompt>, such as freeagent_monthly_bookkeeping, and their text names the prefixed tools (freeagent_list_bank_transactions instead of list_bank_transactions).
Claude Code plugin
The repository is also a Claude Code plugin marketplace. Its freeagent plugin adds the server’s MCP connection and the 14 prompts as slash commands.
Install
In Claude Code:
/plugin marketplace add Trozz/mcp-freeagent
/plugin install freeagent@mcp-freeagent
The plugin connects to http://localhost:7771/freeagent, the address of a server run locally as in Getting started. To use another server, set FREEAGENT_MCP_URL in the environment Claude Code starts in:
export FREEAGENT_MCP_URL=https://freeagent-mcp.example.com/freeagent
Then run /mcp, choose freeagent and authenticate: your browser shows the server’s consent page, then FreeAgent’s login.
Commands
Each prompt is a command named after it, with - for _:
| Command | Prompt |
|---|---|
/freeagent:business-snapshot [focus] | business_snapshot |
/freeagent:monthly-bookkeeping [month] | monthly_bookkeeping |
/freeagent:explain-transactions [bank_account] [period] | explain_transactions |
/freeagent:approve-guesses [bank_account] | approve_guesses |
/freeagent:chase-overdue [tone] [customer] | chase_overdue |
/freeagent:create-invoice <request> | create_invoice |
/freeagent:invoice-unbilled-time [client] | invoice_unbilled_time |
/freeagent:log-time <work> | log_time |
/freeagent:record-expense [details] | record_expense |
/freeagent:vat-check [period] | vat_check |
/freeagent:tax-deadlines [months] | tax_deadlines |
/freeagent:month-end-close [month] | month_end_close |
/freeagent:director-loan-review [as_at] | director_loan_review |
/freeagent:cashflow-review [months] | cashflow_review |
Type the arguments in plain words after the command, for example /freeagent:explain-transactions September 2026 or /freeagent:log-time 3h on the Acme website yesterday. The command reads each argument from what you typed and asks for a required one that is missing. Commands behave as the prompts do: nothing changes in FreeAgent until you agree.
The commands use the plugin’s own freeagent server, whose tools Claude Code shows with a prefix such as mcp__freeagent__.
What is in it
| Path | Contents |
|---|---|
.claude-plugin/marketplace.json | The marketplace, listing the freeagent plugin from ./plugin |
plugin/.claude-plugin/plugin.json | The plugin’s name, description and version |
plugin/.mcp.json | The MCP server: HTTP at ${FREEAGENT_MCP_URL:-http://localhost:7771/freeagent} |
plugin/commands/*.md | One command per prompt |
The command files are generated from the prompts in crates/mcp-freeagent-books/src/prompts.rs, so the commands and the server’s prompts say the same thing. After changing a prompt, regenerate them:
UPDATE_PLUGIN=1 cargo test -p mcp-freeagent-books plugin
A test fails if the files and the prompts drift apart.
Security
mcp-freeagent gives MCP clients access to a company’s books, and is reachable from the internet. This page explains how access is controlled and what the server records.
Secrets
The server holds two secrets: OAUTH_SIGNING_KEY and the FreeAgent app’s FREEAGENT_CLIENT_SECRET.
- Keep both in a secret store, and read them from files with the
_FILEvariables (OAUTH_SIGNING_KEY_FILE,FREEAGENT_CLIENT_SECRET_FILE). Never commit them. - Whoever has
OAUTH_SIGNING_KEYcan mint tokens and open the FreeAgent refresh tokens sealed inside them. Rotating it signs everyone out. - The app secret alone gives no access to anyone’s books: a sign-in also needs that person to log in at FreeAgent and approve the app. FreeAgent lets an app have two secrets at once, so a leaked secret can be replaced without downtime.
The server keeps no FreeAgent credential of its own and no database. Each person’s refresh token lives sealed in their own MCP tokens, plus, when FREEAGENT_TOKEN_STORE is set, an encrypted copy of a replaced one that only their tokens can open.
Sign-in
The server is its own OAuth 2.1 authorization server for MCP clients, and signs people in through FreeAgent; Signing in with FreeAgent has the whole flow.
/freeagentand/mcpare separate OAuth protected resources (RFC 9728), with metadata at/.well-known/oauth-protected-resource/<endpoint>. Tokens are bound to the endpoint they were issued for (RFC 8707).- Every MCP client is shown on the consent page before the browser goes to FreeAgent, because all clients reach FreeAgent under this server’s one app.
- The pending sign-in travels in an encrypted,
HttpOnly,SameSite=Laxcookie bound to a randomstate, so FreeAgent’s code is only accepted from the browser that started the sign-in. - MCP access tokens last 1 hour, refresh tokens 30 days, and a grant at most 90 days. There is no per-client revocation: revoke the app’s access in FreeAgent to cut one person off, or rotate
OAUTH_SIGNING_KEYto sign everyone out. - Clients cannot skip OAuth: there is no static token (
MCP_AUTH_TOKENis refused at startup), and a FreeAgent token sent as a bearer token is not accepted. - MCP sessions are bound to the sign-in that opened them, so nobody can use another person’s session, even knowing its id.
Sign-in limits
- At most 5 failed attempts per minute per client address (an IPv4 address or IPv6 /64), and 25 per network (an IPv4 /24 or IPv6 /48).
- Once 30 sign-ins have been rejected across all addresses in a minute, only addresses with a rejection of their own are refused; everyone else signs in as usual.
- A code FreeAgent refuses counts as a failed attempt; FreeAgent being unreachable does not.
- Tokens already issued keep working throughout.
- The client address is the TCP peer. Behind a reverse proxy, set
TRUSTED_PROXIESto the proxy addresses so the client address fromX-Forwarded-Foris used; otherwise every request shares the proxy’s address.
Read-only mode
FREEAGENT_READ_ONLY=freeagent (or all) makes the FreeAgent service read-only on this server:
- Clients see only the tools marked read-only: the lists, reports,
get_tools andapi_get. - Any other tool call returns
read_only: the freeagent service is read-only on this server, and is audited asrefused. - Prompts stay listed; a prompt step that needs a hidden tool tells the model to say so and skip it.
- It applies on
/freeagentand under/mcp.
Read-only mode limits what the server lets clients do. What a person can see is still decided by their FreeAgent access level.
Writes need agreement
Write tools carry MCP annotations, so clients ask before running them, and deletes and other hard-to-undo changes are marked destructive (see Reads and writes). The server’s instructions and every prompt also tell the model to show the person what will change and wait for agreement.
Text in the books
Contact names, descriptions, bank references and other text in the books are written by customers, suppliers and banks. The server’s instructions and every prompt tell the model to treat them as data, not instructions. Prompt arguments are fenced in their own tags and cannot close them.
Audit log
Every call of a tool that is not read-only, including refused ones, produces one audit line:
{"ts": "2026-10-18T10:00:00Z", "service": "freeagent", "endpoint": "/freeagent", "tool": "create_invoice", "outcome": "ok", "error_kind": null, "caller": "oauth:<client_id>", "subject": "freeagent:example-ltd:user:7", "elapsed_ms": 412}
outcomeisok,errororrefused(a read-only service);error_kindis the error kind, such asvalidation(read_onlyfor a refusal), ornullon success.subjectis the FreeAgent user who signed in, asfreeagent:<company subdomain>:user:<id>.- Arguments, ids and results are never recorded.
- Lines go to the
auditlog target, which stays on atinfowhateverLOG_LEVELsays, and are appended toAUDIT_LOG_PATHwhen it is set (the file is created with mode 0600). - If the file cannot be written, the server logs a warning at most once a minute and the tool call still succeeds.
- In Docker, mount a volume for the file, for example
./audit:/auditwithAUDIT_LOG_PATH=/audit/audit.jsonl, so it survives container restarts.
What is never logged
- The app secret, refresh and access tokens, MCP tokens and the
Authorizationheader. - The books’ content: invoice lines, contact details, transaction descriptions, tool results and FreeAgent’s response bodies.
Tool error messages, which can quote ids and values, are logged only at debug level. The exception is DEBUG_UNSAFE_LOG_CONTENT=true, which writes tool results and FreeAgent response bodies into the logs for debugging and prints a warning at startup. Credentials are never logged, even then.
Talking to FreeAgent
- Every request uses TLS with certificate verification, to the configured API host only.
FREEAGENT_API_URLmust behttps, except a loopback address for tests. - Redirects are never followed, and
api_getandapi_requestrefuse URLs on any other host, so a person’s access token never leaves for another address. - Revoking the app’s access in FreeAgent, or deleting the app in the Developer Dashboard, cuts the server off.
The container
The image is FROM scratch: the static binary and CA certificates only, running as UID 65532.
Operations
Health
GET /healthzreturnsokwithout authentication. It does not contact FreeAgent, so a FreeAgent outage does not get the container restarted.mcp-freeagent --healthcheckconnects to127.0.0.1on theBIND_ADDRport and exits 0 when/healthzanswers. The container image uses it as itsHEALTHCHECK, sodocker psshowshealthy.
Logs
- Logs go to stdout, as JSON by default (
LOG_FORMAT=prettyfor humans). - Every tool call logs a
tool callline with the tool, outcome and duration, and a failed one atool failedwarning with its error kind. Startup logsfreeagent settings(API address and the app’s client id),service enabledandcombined endpoint enabled. - A sign-in logs
signed in to FreeAgentwith the person’s subject. LOG_LEVELtakestracingfilters, for exampleinfo,mcp_freeagent=debug. Avoiddebugortracefor everything (LOG_LEVEL=debug): that also turns on the HTTP libraries’ own debug output, which this server does not cap. Raise only themcp_freeagenttarget, or useDEBUG=true.DEBUG=trueadds each FreeAgent request’s method, path, status and duration, retries, token requests and tool error messages, without response bodies.DEBUG_UNSAFE_LOG_CONTENT=trueadds tool results and FreeAgent response bodies. Use it only briefly; see Security.
Metrics
METRICS_ADDR (for example 0.0.0.0:9090) starts a separate plain-HTTP Prometheus listener. Keep it on an internal network. Metrics:
| Metric | What it counts |
|---|---|
mcp_tool_calls_total, mcp_tool_duration_seconds | Tool calls by tool and outcome, and their duration |
freeagent_requests_total, freeagent_request_duration_seconds | FreeAgent API requests by endpoint label and status class, and their duration |
freeagent_rate_limited_total | API requests FreeAgent refused with 429 |
freeagent_token_requests_total | Requests to FreeAgent’s token endpoint by grant (authorization_code or refresh_token) and HTTP status |
freeagent_refresh_token_rotations_total | Refreshes where FreeAgent handed out a new refresh token |
freeagent_token_store_errors_total | Failed writes of FREEAGENT_TOKEN_STORE |
oauth_requests_total, oauth_login_failures_total | Requests to the server’s own OAuth endpoints, and failed sign-ins |
http_requests_total | HTTP requests by route and status |
freeagent_rate_limited_total rising means people are reaching FreeAgent’s limit of 120 requests a minute and 3600 an hour per user. freeagent_token_store_errors_total above zero means replaced refresh tokens may not survive a restart: check the file’s directory is writable by the server.
Traces
OTEL_EXPORTER_OTLP_ENDPOINT, with the standard OTEL_EXPORTER_OTLP_HEADERS when your collector needs them, exports traces over OTLP/HTTP. Nothing is exported unless it is set.
Audit file
With AUDIT_LOG_PATH, the audit file only grows: one short line per write. Rotate it with a tool that truncates in place, such as logrotate with copytruncate. See Security for the line format.
Upgrading
- Docker: pull the new image and recreate the container (
docker compose pull && docker compose up -d). Keep theFREEAGENT_TOKEN_STOREvolume. - Binary: replace the file and restart.
- Connectors stay signed in across upgrades and restarts as long as
OAUTH_SIGNING_KEY,PUBLIC_URL,FREEAGENT_CLIENT_IDand the FreeAgent environment stay the same, and the token store is kept. - Release notes list every change; see Releases.
Backups
The books live in FreeAgent; the server keeps only caches in memory. Keep your configuration and secrets somewhere safe, and keep the FREEAGENT_TOKEN_STORE file on a persistent volume. Losing it does not lose data: at worst, people whose refresh token FreeAgent replaced sign in again.
Scaling
Run one replica. Access tokens, sign-in limits and MCP sessions live in memory per replica, and the token store is one file per replica. If you need more than one, send each person to the same replica (sticky sessions), and give each replica its own token store file.
Resource use
Memory holds each signed-in person’s current FreeAgent access token (at most 10,000 sign-ins at once; the least recently used are dropped first and simply refreshed again). The container needs no writable filesystem apart from the token store and audit volumes.
Troubleshooting
The server does not start
The server lists every configuration problem at startup, each on a configuration error: line, and exits. Common ones:
| Message | Fix |
|---|---|
PUBLIC_URL must be an https URL (http is only allowed for localhost) | Set PUBLIC_URL to the external https address, without a path |
OAUTH_SIGNING_KEY must be at least 32 bytes | Use openssl rand -hex 32 |
FREEAGENT_CLIENT_ID is required, FREEAGENT_CLIENT_SECRET is required | Set the app’s OAuth identifier and secret from the FreeAgent Developer Dashboard |
FREEAGENT_CLIENT_ID must be the OAuth identifier from the FreeAgent Developer Dashboard (letters, digits, - and _) | Copy the OAuth identifier, not the app’s name |
FREEAGENT_ENVIRONMENT must be production or sandbox, got "..." | Use production or sandbox |
FREEAGENT_API_URL must use https (http is only allowed for loopback addresses) | Leave it unset unless you test against a local fake |
FREEAGENT_API_VERSION must be a date as YYYY-MM-DD, such as 2026-09-01 | Use a date, or leave it unset |
MCP_AUTH_TOKEN cannot be used when people sign in with their own FreeAgent account | Remove MCP_AUTH_TOKEN; every client signs in with OAuth |
FREEAGENT_TOKEN_STORE: cannot read ... or ... is not a FreeAgent token store: ... | The file exists but is unreadable by UID 65532, or is something else. Point it at a new path; the file is created on the first write |
..._FILE: cannot read ... | The secret file is missing or unreadable by UID 65532 in the container |
FreeAgent shows an error instead of its login
- The redirect URI does not match. Register exactly
<PUBLIC_URL>/callbackwith the app, scheme and port included, for examplehttp://localhost:7771/callbackfor local use.PUBLIC_URLmust be exactly the address the server is reached at. - Wrong environment. A sandbox company needs
FREEAGENT_ENVIRONMENT=sandbox, and the live oneproduction(the default).
The sign-in page reports a problem
| The page says | Cause and fix |
|---|---|
FreeAgent refused this server's app credentials; ask the server's operator to check them | FREEAGENT_CLIENT_ID or FREEAGENT_CLIENT_SECRET is wrong, or the secret was replaced. The log has FreeAgent refused this server's OAuth app: check FREEAGENT_CLIENT_ID and FREEAGENT_CLIENT_SECRET |
FreeAgent is limiting requests; try again in a minute | FreeAgent’s rate limit. Wait a minute |
FreeAgent granted no refresh token | FreeAgent’s answer had no refresh token, so the sign-in cannot last. Try again; report it if it repeats |
| An error page after coming back from FreeAgent | The sign-in took more than 10 minutes, or was finished in another browser than it started in. Start the connection again from the client |
The login form expired or was modified. Start the connection again. | The consent page was open for more than 10 minutes. Start again |
Too many attempts from this address ... | Too many failed sign-ins from this address. Wait a minute. Behind a proxy, check TRUSTED_PROXIES |
claude.ai cannot connect
- The server must be reachable from the internet with a publicly trusted certificate. A self-signed certificate works only behind a tunnel or proxy; see TLS and public access.
- With a Cloudflare tunnel, the public hostname must point to
https://mcp-freeagent:8443with No TLS Verify on. PUBLIC_URLmust be exactly the address claude.ai uses. OAuth metadata, token audiences and the FreeAgent redirect URI are built from it.
A connector stops working
- Tools fail with
auth: FreeAgent no longer accepts this connection's sign-in ...: FreeAgent refused the refresh token. It was revoked, expired, or replaced by FreeAgent and then lost in a restart withoutFREEAGENT_TOKEN_STORE. Reconnect the connector, or run/mcpin Claude Code. - The client gets 401 everywhere:
OAUTH_SIGNING_KEYorPUBLIC_URLchanged, which signs every client out. Remove the connector and add it again. - Everyone had to sign in again after a configuration change: changing
FREEAGENT_ENVIRONMENT,FREEAGENT_API_URLorFREEAGENT_CLIENT_IDends every sign-in. - 90 days after signing in, every grant ends and the person signs in again.
- A token for
/freeagentis not accepted on/mcp, and the other way round. Make sure the connector URL is the endpoint it signed in to.
Tool errors
Tool errors start with a kind, such as permission: ...; Working with the tools lists them. The common ones:
| Error | What to do |
|---|---|
permission: FreeAgent refused ... (HTTP 403) ... | The signed-in user’s access level does not allow it, or the feature does not apply to this company. get_current_user shows the level |
rate_limited: the FreeAgent API rate limit ... is used up; try again in N seconds | Wait as long as it says. The limit is per FreeAgent user |
validation: FreeAgent rejected ... | FreeAgent refused the request; the rest of the message is FreeAgent’s own reason |
internal: FreeAgent refused this server's OAuth app credentials ... | The operator needs to check FREEAGENT_CLIENT_ID and FREEAGENT_CLIENT_SECRET |
upstream: ... returned invalid JSON ...; check FREEAGENT_API_URL points at the FreeAgent API | FREEAGENT_API_URL points somewhere else |
read_only: the freeagent service is read-only on this server | FREEAGENT_READ_ONLY is set |
Warnings in the log
FreeAgent refused this app's credentials as HTTP Basic but accepted them in the request body; sending them in the body from now on: harmless; the server adapted. If FreeAgent refuses them both ways, check the app’s id and secret.writing the FreeAgent token store failed: the token store file or its directory is not writable by the server. Replaced refresh tokens are then kept only in memory.could not write the audit log:AUDIT_LOG_PATHis not writable. Tool calls still succeed.
More detail
Set LOG_LEVEL=info,mcp_freeagent=debug or DEBUG=true and reproduce the problem. These log each FreeAgent request’s method, path and status, and the full text of tool errors, but not response bodies. When reporting an issue, include the version (mcp-freeagent --version) and the log lines, and check that they contain nothing private.
Architecture
Request flow
flowchart LR
C1["MCP client<br/>/freeagent"] --> T
C2["MCP client<br/>/mcp"] --> T
B["Browser<br/>/authorize, /callback"] --> T
T["HTTPS<br/>tunnel, proxy or direct"] --> S
subgraph S["mcp-freeagent binary (:8443)"]
direction TB
P["Public routes<br/>/healthz, /favicon.ico<br/>/.well-known/*, /register<br/>/authorize, /callback, /token"]
G["Bearer check per endpoint<br/>token audience, sealed refresh token"]
W["Policy wrapper<br/>read-only and audit"]
F["FreeAgent service<br/>tools and prompts"]
X["Combined /mcp<br/>prefixed names"]
K["Token cache<br/>access tokens per person"]
A["API client<br/>retries, status mapping"]
G --> W
W --> F
W --> X
X --> F
F --> A
A --> K
end
K -->|"token_endpoint"| FA["api.freeagent.com/v2"]
A -->|"API v2"| FA
P -.->|"approve_app redirect"| FA
Crates
| Crate | Role |
|---|---|
mcp-server-core (from mcp-server-core-rs) | Configuration reading, the OAuth authorization server and upstream sign-in, bearer guards, TLS, logging, metrics, the read-only and audit wrapper, the combined endpoint, and the Service trait |
mcp-freeagent-books | The freeagent service: settings (config.rs), FreeAgent OAuth, access tokens and the token store (oauth.rs), sign-in through FreeAgent (verifier.rs), the API client (api.rs), the tools (tools/), output shaping (view.rs) and the prompts (prompts.rs) |
mcp-freeagent | The binary: registers the service, sets the FREEAGENT variable prefix and the sign-in mode, and runs the server |
mcp-server-core is taken from git at the commit that adds upstream OAuth sign-in, until that is released to crates.io.
A tool call, end to end
sequenceDiagram
participant C as Client
participant S as mcp-freeagent /freeagent
participant F as FreeAgent
C->>S: tools/call list_invoices (Bearer MCP token)
S->>S: verify token, open the sealed refresh token
alt no cached access token, or it expires within 2 minutes
S->>F: POST token_endpoint (refresh_token)
F-->>S: access token, maybe a new refresh token
S->>S: keep the new refresh token (memory and token store)
end
S->>F: GET /v2/invoices?view=...&page=1&per_page=25
F-->>S: invoices, X-Total-Count, Link
S->>S: unwrap, drop empty values, add ids
S-->>C: {count, total, page, next_page, items}
Design choices
- No database. FreeAgent is the only store. The server keeps access tokens in memory, and the token store file holds only replaced refresh tokens, encrypted per person.
- People sign in as themselves. The server holds an OAuth app, not a credential. Every call runs with the signed-in person’s FreeAgent token, so FreeAgent’s own access levels decide what they can do.
- Writes are never retried once they reach FreeAgent, so a slow create cannot happen twice. Reads are retried once.
- Compact answers. FreeAgent’s JSON is unwrapped, empty values are dropped and every
urlgets anidbeside it, so models spend fewer tokens and can pass ids back directly. Attachments lose their signed download links (content_srcand its thumbnails, withexpires_at): each is about 2,000 characters and FreeAgent issues it for only 30 seconds. Lists of locked fields and people’s National Insurance numbers and tax references are left out too, and a page too long for a tool result is refused with atoo_largeerror that says whatper_pagefits. - Safe defaults. Write tools are annotated, prompts wait for agreement, and the whole service can be made read-only.
Contributing
Build and test
You need Rust 1.99.1 (the workspace pins it).
cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --all --check
cargo deny check
bash scripts/test-next-version.sh
The tests run against an in-memory fake of the FreeAgent API (crates/mcp-freeagent-books/tests/support/fake_freeagent.rs) with a real token endpoint, expiring access tokens and optionally rotating refresh tokens. They cover the whole sign-in through FreeAgent and MCP sessions through the OAuth and bearer guards, so no FreeAgent account is needed. To try changes against real books, run the server with FREEAGENT_ENVIRONMENT=sandbox and a sandbox company.
Adding or changing a tool
Tools live in crates/mcp-freeagent-books/src/tools/, one module per area. A test checks every tool has a description and the right annotations: names starting get_, list_ or search_, business_snapshot and api_get must be read-only, and every delete_ tool, mark_tax_return and api_request must be destructive. Tool names must stay short enough for the freeagent_ prefix on /mcp.
Document a new tool on its page under docs/src/tools/, and a new variable in docs/src/configuration.md.
Prompts and the plugin
Prompts are in crates/mcp-freeagent-books/src/prompts.rs. The Claude Code plugin’s command files are generated from them; after changing a prompt, run:
UPDATE_PLUGIN=1 cargo test -p mcp-freeagent-books plugin
A test fails if the command files and the prompts drift apart, and another checks that prompts name only tools that exist.
This documentation
The site is built with mdBook from docs/. To preview it:
cargo install --locked mdbook@0.5.4 mdbook-mermaid@0.17.1 lychee@0.24.2
bash scripts/build-docs.sh
mdbook serve docs --open
scripts/build-docs.sh builds the book and checks every internal link and anchor.
Pull requests
- Branch from
developasfeature/<name>,bugfix/<name>orhotfix/<name>, and open the pull request againstdevelop. - Use conventional commit messages (
feat:,fix:,docs:,test:,chore:,refactor:). - Test data must be synthetic: never copy real books, contacts or bank transactions into fixtures.
- CI runs fmt, clippy, tests, cargo-deny, a Docker build, the script tests and the documentation build.
Releases
- Work happens on
feature/*andbugfix/*branches merged intodevelopby pull request. - Every merge into
developthat touches the server (crates/,Cargo.toml,Cargo.lockor theDockerfile) publishes a pre-releasevX.Y.Z-dev.N: a GitHub pre-release and image tagsX.Y.Z-dev.Nanddevelop. - A pull request from
developintomainpublishes a releasevX.Y.Zwhen merged: image tagsX.Y.Z,X.Y,Xandlatest, binaries for Linux x86_64 and arm64 and macOS arm64 with checksums, and this documentation site. - The version bump comes from the
developtomainpull request: amajor,minororpatchlabel, otherwise[major],[minor]or[patch]in its title, otherwise patch. - Pull requests into
mainmust come fromdevelopin this repository; CI checks it.
Images are published to ghcr.io/trozz/mcp-freeagent. Pin a version tag such as ghcr.io/trozz/mcp-freeagent:0.1.0 in production, and read the release notes before upgrading.
Repository setup (maintainers, once)
gh label create major --color B60205 --description "Release: major version bump"
gh label create minor --color FBCA04 --description "Release: minor version bump"
gh label create patch --color 0E8A16 --description "Release: patch version bump"
- Under Settings > Actions > General > Workflow permissions, the workflows must be allowed to grant
contents: write,packages: write,id-token: write,attestations: writeandpages: write(the jobs request them explicitly). - Under Settings > Pages, the source must be GitHub Actions for this site to publish.
- After the first image is published, set the
mcp-freeagentpackage visibility to public under Packages for anonymous pulls.