Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

EndpointWhat it does
/freeagent86 tools and 14 prompts for the books of the company whose FreeAgent user signed in
/mcpEvery 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_get and api_request reach 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=freeagent hides 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 scratch container 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:

PurposeAddress
The live APIhttps://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 tokenstoken_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_return only 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_payroll reads 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.

  1. Open the FreeAgent Developer Dashboard and create an app.
  2. Note its OAuth identifier and OAuth secret. They become FREEAGENT_CLIENT_ID and FREEAGENT_CLIENT_SECRET.
  3. Add the redirect URI <PUBLIC_URL>/callback, for example https://freeagent-mcp.example.com/callback. For local use, add http://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 with openssl rand -hex 32 and 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 (or all) hides and refuses every write tool. Reports, lists and api_get keep working. See Security.
  • FREEAGENT_COMBINED=false turns off the combined /mcp endpoint.
  • FREEAGENT_SERVICES selects 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_ID is the app’s OAuth identifier (8 to 128 letters, digits, - and _).
  • FREEAGENT_CLIENT_SECRET is 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 example https://freeagent-mcp.example.com/callback or http://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
  1. Consent. GET /authorize shows 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.
  2. To FreeAgent. The button to continue to FreeAgent sets a cookie holding the pending request, encrypted under a key derived from OAUTH_SIGNING_KEY and bound to a random state. It is HttpOnly, SameSite=Lax, limited to /callback, Secure over https, and lasts 10 minutes. Your browser goes to FreeAgent’s approve_app page.
  3. Back. FreeAgent sends the browser to <PUBLIC_URL>/callback. The server checks state against the cookie, so FreeAgent’s code is only accepted from the browser that started the sign-in, and exchanges the code at FreeAgent’s token_endpoint.
  4. Who you are. The server reads users/me and company to name you as freeagent:<company subdomain>:user:<user id> (or freeagent: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.
  5. To the client. The browser returns to the client with an authorization code, which the client exchanges at /token for 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 in freeagent_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:

LevelAccess
0None
1Time
2My money
3Contacts and projects
4Invoices, estimates and files
5Bills
6Banking
7Tax, accounting and users
8Full

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

EventEffectWhat the person does
The MCP access token is an hour old401 on the endpointNothing: the client refreshes
The client has not refreshed for 30 daysIts refresh token has expiredSigns in again
90 days since sign-inEvery grant lasts at most 90 daysSigns 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 changesEvery grant endsSigns in again
OAUTH_SIGNING_KEY or PUBLIC_URL changesEvery token and client registration stops workingRemoves 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:

EndpointConnector URLTool names
FreeAgenthttps://freeagent-mcp.example.com/freeagentlist_invoices
All serviceshttps://freeagent-mcp.example.com/mcpfreeagent_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).

  1. In claude.ai open Settings, then Connectors, then Add custom connector.
  2. Enter the connector URL, for example https://freeagent-mcp.example.com/freeagent.
  3. 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 /mcp works only there, and a token for /freeagent does not work on /mcp.
  • FREEAGENT_READ_ONLY applies there too: the write tools are hidden and refused.
  • Audit lines name the real service and tool, with "endpoint": "/mcp".
  • FREEAGENT_COMBINED=false turns it off; /mcp then 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 _FILE to its name, for example FREEAGENT_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, on and off.
  • Lists are comma separated; spaces around names are ignored.

Server and HTTP

VariableRequiredDefaultExampleDescription
PUBLIC_URLyeshttps://freeagent-mcp.example.comExternal 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_ADDRno0.0.0.0:8443127.0.0.1:7771Listen 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_PATHno/certs/fullchain.pem, /certs/privkey.pemPEM certificate chain and private key. Both or neither; reloaded automatically when the files change. See TLS and public access
INSECURE_HTTPnofalsetrueServe plain HTTP. For local use, or when TLS is terminated in front of the server on a network you trust
ALLOWED_ORIGINSnohttp://localhost:6274Extra browser Origin values accepted on MCP requests, comma separated. The PUBLIC_URL origin is always allowed
TRUSTED_PROXIESno10.0.0.2,10.0.0.3Proxy IP addresses whose X-Forwarded-For is trusted for sign-in rate limiting

Sign-in and tokens

VariableRequiredDefaultExampleDescription
OAUTH_SIGNING_KEYyesoutput of openssl rand -hex 32Key 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_IDyesabcd1234EFGH5678The FreeAgent app’s OAuth identifier: 8 to 128 letters, digits, - and _. Changing it signs everyone out
FREEAGENT_CLIENT_SECRETyesthe app’s OAuth secretThe FreeAgent app’s OAuth secret
FREEAGENT_TOKEN_STOREno/data/tokens.jsonFile 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

VariableRequiredDefaultExampleDescription
FREEAGENT_ENVIRONMENTnoproductionsandboxproduction (or live) for the live API, sandbox for FreeAgent’s sandbox. Anything else stops startup. Changing it signs everyone out
FREEAGENT_API_URLnofrom FREEAGENT_ENVIRONMENThttp://127.0.0.1:9999/v2The 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_VERSIONno2026-09-01An X-Api-Version date to send with every API request, as YYYY-MM-DD

Services

VariableRequiredDefaultExampleDescription
FREEAGENT_SERVICESnoall (freeagent)freeagentServices to run. There is one, freeagent. An unknown name or an empty list stops startup
FREEAGENT_READ_ONLYnononefreeagent or allServices whose write tools are hidden and refused, on their own endpoint and under /mcp. An unknown name stops startup. See Security
FREEAGENT_COMBINEDnotruefalseServe the combined endpoint /mcp. With false, /mcp returns 404

Logging, metrics and audit

VariableRequiredDefaultExampleDescription
LOG_LEVELnoinfoinfo,mcp_freeagent=debugLog 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_FORMATnojsonprettyjson or pretty
DEBUGnofalsetrueDebug 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_CONTENTnofalsetrueAlso 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_ADDRno0.0.0.0:9090Starts a separate plain-HTTP Prometheus listener. Keep it on an internal network. See Operations
OTEL_EXPORTER_OTLP_ENDPOINTnohttp://otel-collector:4318Exports traces over OTLP/HTTP. The standard OTEL_EXPORTER_OTLP_HEADERS is honoured. Nothing is exported unless it is set
AUDIT_LOG_PATHno/audit/audit.jsonlFile 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:

  1. 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.
  2. TLS_CERT_PATH and TLS_KEY_PATH both 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.
  3. Neither set: the server generates an in-memory self-signed certificate for the PUBLIC_URL host, localhost, 127.0.0.1 and ::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 set INSECURE_HTTP=true if the proxy and server share a trusted network.
  • Pass the Host header through unchanged and do not buffer responses (MCP uses streaming HTTP responses).
  • Set TRUSTED_PROXIES to the proxy’s IP address so the server uses the client address from X-Forwarded-For for 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.

AreaToolsPage
Company5Company and contacts
Contacts and notes7Company and contacts
Projects and tasks7Projects and time
Timeslips and timers6Projects and time
Invoices, estimates, credit notes18Sales
Bills, expenses and mileage11Purchases
Bank accounts, transactions and explanations11Banking
Categories, reports, journals, tax returns, payroll12Accounting and tax
Any other FreeAgent endpoint2Any 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 and api_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: every delete_*, invoice_action, mark_tax_return and api_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, or 750-1 for a sub-account) or as the FreeAgent URL a tool returned (https://api.freeagent.com/v2/contacts/2). Results carry an id beside every url. Never guess an id: find it with a list_ 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_date must not be after to_date.
  • Signs follow FreeAgent. Bank money out is negative and money in positive. An expense’s gross_value is negative when it is owed to the claimant, but create_expense and update_expense take what was spent as a positive amount.
  • Categories are nominal codes such as 285 or 001. list_categories finds 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.
  • extra on 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 a file_name and optionally a content_type (application/pdf, image/png, image/jpeg or image/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 and expires_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_locked and locked_reason stay.
  • ni_number and unique_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:

KindMeaning
authFreeAgent no longer accepts this connection’s sign-in (revoked, expired or replaced). Sign in again: reconnect the connector, or run /mcp in Claude Code
permissionFreeAgent refused (HTTP 403): the signed-in user’s access level does not allow it, or the feature does not apply to this company
not_foundNothing at that id or path
rate_limitedFreeAgent’s limit of 120 requests a minute and 3600 an hour per user is used up. The message says how long to wait
validationAn argument is wrong, or FreeAgent rejected the request (HTTP 400, 406, 409 or 422); the message says which
upstreamFreeAgent could not be reached, timed out or answered unexpectedly; usually temporary
internalA problem inside the server, such as FreeAgent refusing the server’s own app credentials; check the log
read_onlyThe service is read-only on this server (FREEAGENT_READ_ONLY)
too_largeA 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

ToolKindWhat it doesKey parameters
get_companyreadThe 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 contextnone
get_current_userreadThe 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 resultnone
list_usersreadThe company’s FreeAgent users (directors, employees, accountants) with their ids, roles and permission levels. Needs the tax, accounting and users access levelview: all (default), staff, active_staff, advisors or active_advisors
get_tax_timelinereadUpcoming and recent deadlines for VAT returns, corporation tax, self assessment, payroll and Companies House filings, with amounts due where knownnone
business_snapshotreadWhere 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 deadlinesnone

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_transactions and explanations_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 unavailable with 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

ToolKindWhat it doesKey parameters
search_contactsreadFind 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_balancequery, view, sort, updated_since, page, per_page
get_contactreadOne contact in full: names, emails, phones, address, payment terms, VAT settings, account_balance and active projects countid
create_contactwriteCreate a customer or supplier. Give organisation_name, or first_name and last_name. Search first so you do not create a duplicatecontact fields (below)
update_contactwriteChange only the fields given. status Hidden hides it from listsid, contact fields, status (Active or Hidden)
delete_contactwrite, destructiveDelete a contact. FreeAgent refuses when it has invoices, bills or projects: hide it with update_contact insteadid
list_notesreadThe notes on one contact or project, newest first, with author and datescontact_id or project_id
create_notewriteAdd a note to a contact or project, for example a record of a call or a payment promisenote, 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_suppliers or hidden.
  • sort: name (default), created_at or updated_at; prefix - for newest first, such as -updated_at.
  • updated_since: YYYY-MM-DD or 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

ToolKindWhat it doesKey parameters
list_projectsreadProjects with their client (contact), status, budget, billing rate and currencycontact_id, view: active (default), completed, cancelled or hidden; page, per_page
get_projectreadOne project in full: client, status, budget, billing rate, dates and currencyid
create_projectwriteCreate a project for a client. status defaults to Active, budget_units to Hours and currency to the company’scontact_id, name, project fields (below)
update_projectwriteChange only the fields given. Set status Completed to close itid, project fields
list_tasksreadTasks, optionally for one project, with billing rate and whether they are billableproject_id, view: all (default), active, completed or hidden; updated_since, page, per_page
create_taskwriteCreate a task on a project, such as Development or Meetings, so time can be logged against itproject_id, name, billing_rate, billing_period (hour or day), is_billable (default true), status
update_taskwriteChange only the fields givenid, 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

ToolKindWhat it doesKey parameters
list_timeslipsreadLogged time with date, hours, comment, task, project and user, and whether each is billed. view unbilled shows time not yet invoiced; running shows live timersview: all (default), unbilled or running; project_id, task_id, user_id, from_date, to_date, updated_since, nested, page, per_page
log_timewriteCreate one or more timeslips. The user defaults to the signed-in user and the project to the task’s own. Returns the timeslips createdentries (1 to 100, below)
update_timeslipwriteChange a timeslip’s hours, date, comment or task. Billed timeslips cannot be changedid, hours, dated_on, comment, task_id
delete_timeslipwrite, destructiveDelete a timeslipid
start_timerwriteStart the timer on a timeslip. To time new work, create one with log_time and hours 0 first. Only one timer runs at a timeid
stop_timerwriteStop the timer; the timeslip’s hours then include the time timedid

nested: true on list_timeslips includes each timeslip’s user, project and task in full.

Timeslip entries

Each entry of log_time’s entries:

FieldRequiredMeaning
task_idyesThe task worked on (list_tasks)
dated_onyesThe day, YYYY-MM-DD
hoursyesHours as a decimal: 1h30 is 1.5. 0 with start_timer to time it live
commentno
project_idnoDefault: the task’s own project
user_idnoWho 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

ToolKindWhat it doesKey parameters
list_invoicesreadInvoices with reference, contact, dates, status (Draft, Open, Overdue, Paid and so on), total_value and due_valueview, contact_id, project_id, sort, updated_since, with_items, page, per_page
get_invoicereadOne invoice in full, with its line items, totals, VAT, what is paid and due, and its payment linkid
create_invoicewriteCreate a draft invoice from line items, a project’s unbilled time and expenses, or both. Returns it with its id and totalscontact_id, items, invoice fields (below)
update_invoicewriteChange 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 firstid, invoice fields
delete_invoicewrite, destructiveDelete a draft invoice. Sent invoices are refused: cancel them with invoice_action mark_as_cancelled, or issue a credit noteid
invoice_actionwrite, destructiveMove an invoice through its life (below)id, action
list_recurring_invoicesreadRecurring invoice profiles FreeAgent invoices from on a schedule, with frequency, next_recurs_on and statuscontact_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

FieldMeaning
contact_idThe customer. Required on create
itemsLine items (below), up to 100
dated_onThe invoice date. Default on create: today
payment_terms_in_daysDays until due; 0 means due on receipt. Default on create: the contact’s payment terms, otherwise 30
due_onA fixed due date instead of payment terms
referenceInvoice number. Default: the next in sequence
currencyISO 4217 code. Default: the company’s currency
commentsText shown on the invoice, such as payment details or thanks
discount_percent, po_reference, project_id
ec_statusUK/Non-EC (default), EC Goods, EC Services, Reverse Charge or EC VAT MOSS
include_timeslips, include_expensesA project’s unbilled time and rebillable expenses; see below. Need project_id
extraAny 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 as billed_grouped_by_single_timeslip, billed_grouped_by_timeslip, billed_grouped_by_timeslip_task or billed_grouped_by_timeslip_date.
  • include_expenses: its rebillable expenses, grouped as billed_grouped_by_single_expense or billed_grouped_by_expense.

Invoice actions

invoice_action action:

ActionEffect
mark_as_sentMarks it sent without emailing it. Also re-opens a cancelled invoice
mark_as_draftBack to draft, so it can be edited
mark_as_scheduledTo be emailed by FreeAgent
mark_as_cancelledWrites off an unpaid invoice
convert_to_credit_noteMakes it a draft negative invoice
duplicateA 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

ToolKindWhat it doesKey parameters
list_estimatesreadEstimates and quotes with reference, contact, status and totalsview: 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_estimatereadOne estimate or quote in full, with its itemsid
create_estimatewriteCreate a draft estimate, quote or proposal from line itemscontact_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_actionwritemark_as_sent, mark_as_draft, mark_as_approved, mark_as_rejected, convert_to_invoice (makes a draft invoice from it) or duplicateid, action

Credit notes

ToolKindWhat it doesKey parameters
list_credit_notesreadCredit notes with reference, contact, status and valuesview: 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_notereadOne credit note in full, with its itemsid
create_credit_notewriteA draft credit note for a customer, for example to credit part of an invoice. Prices are positivecontact_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:

FieldMeaning
descriptionWhat was sold, as it reads on the document. Required for a new item
quantityHow many, such as 7.5. Default for a new item: 1
pricePrice per unit before VAT, such as 80
item_typeHours, Days, Weeks, Months, Years, Products, Services, Training, Expenses, Comment, Bills, Discount, Credit, VAT or Stock; leave out for no unit
categoryIncome category as a nominal code, such as 001 (Sales). Default: the company’s sales category
sales_tax_rateVAT 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_statusTAXABLE, EXEMPT or OUT_OF_SCOPE
id, deleteOn 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

ToolKindWhat it doesKey parameters
send_document_emailwriteEmail 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 sentdocument (invoice, estimate or credit_note), id, subject and body, or use_template; to, from, email_to_sender
get_document_pdfreadThe PDF of an invoice, estimate or credit note, as an embedded application/pdf resource, for example to attach or savedocument, id
list_email_addressesreadThe verified addresses FreeAgent can send from, for send_document_email’s fromnone
list_price_list_itemsreadThe price list: saved products and services with code, description, price, unit and VAT, to reuse as invoice linessort: created_at, code or updated_at; page, per_page

send_document_email details:

  • to is comma-separated addresses. Default: the contact’s billing email, otherwise its main email.
  • from must be a verified address from list_email_addresses. Default: FreeAgent’s.
  • use_template: true sends FreeAgent’s own email template instead of subject and body. FreeAgent adds the view and pay link either way.
  • email_to_sender sends 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 with paid_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

ToolKindWhat it doesKey parameters
list_billsreadBills with reference, supplier, dates, status, total_value and due_value. view open_or_overdue shows what the company owesview: 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_billreadOne bill in full, with its lines, VAT and what is paid and dueid
create_billwriteRecord 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 givencontact_id, reference, dated_on, due_on, items, attachment, currency, comments, ec_status, extra
update_billwriteChange only the fields given. items adds lines; an item with id changes that line, and with id and delete: true removes itid, bill fields
delete_billwrite, destructiveDelete a billid

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:

FieldMeaning
categoryExpense category as a nominal code, such as 285 (Accommodation and Meals). Required
total_valueThe line’s total including VAT, such as 120.00
total_value_ex_taxOr 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_rateVAT percentage, such as 20. Default: from the category
sales_tax_statusTAXABLE, EXEMPT or OUT_OF_SCOPE
manual_sales_tax_amountAn exact VAT amount, overriding the rate
id, deleteOn update: the line to change, and delete: true to remove it

Expenses and mileage

ToolKindWhat it doesKey parameters
list_expensesreadExpense 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_expensereadOne expense or mileage claim in full: user, category, date, amounts, VAT, receipt and rebillingid
create_expensewriteRecord an expense someone paid personally: category, date, description and the amount spent including VAT, optionally with the receiptexpense fields (below)
create_mileage_claimwriteClaim business mileage at HMRC’s approved rates. FreeAgent works out the amountdated_on, description, mileage, and the fields below
update_expensewriteChange only the fields given. amount is what was spent, positiveid, expense fields
delete_expensewrite, destructiveDelete an expenseid

Expense fields

FieldMeaning
amountWhat was spent, including VAT, as a positive amount such as 42.50. The server stores it with FreeAgent’s sign
refundtrue when the claimant paid money back to the company instead
categoryExpense category as a nominal code, such as 285; see list_categories
dated_on, description, receipt_reference
user_idWho paid and is owed it. Default on create: the signed-in user
currencyISO 4217 code when not the company’s currency
sales_tax_rateVAT percentage. Default: from the category
manual_sales_tax_amountAn exact reclaimable VAT amount, overriding the rate
project_id, rebill_typeA project to rebill it to, and how: cost, markup or price
attachmentThe receipt
extraAny other expense field by FreeAgent’s name

Mileage fields

FieldMeaning
dated_on, descriptionRequired. The description says where and why, such as “Leeds to Manchester, client meeting”
mileageRequired. Distance in the company’s mileage units (miles unless set to kilometres)
vehicle_typeCar (default), Motorcycle or Bicycle
engine_typePetrol (default), Diesel, LPG, Electric, Electric (Home charger) or Electric (Public charger)
engine_sizeFrom FreeAgent’s mileage settings, such as “Up to 1400cc”; needed for VAT on fuel
have_vat_receiptWhether there is a VAT receipt for the fuel
reclaimReclaim at the HMRC approved rate. Default: true; false only rebills it
user_idWho drove. Default: the signed-in user
project_id

Attachments

attachment on bills, expenses and bank explanations:

FieldMeaning
file_nameRequired, such as receipt.pdf
data_base64Required. The file, base64-encoded
content_typeapplication/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.

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:

ToolKindWhat it doesKey parameters
create_upload_linkwriteA 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 modeltarget (expense, bill or bank_transaction_explanation) and id, or neither
get_upload_statusreadwaiting (with the last error, if a try failed), uploading, received (held for the model) or attachedupload_url
get_uploaded_filereadThe held file: a photo as an image the model can read, a PDF as an embedded fileupload_url
get_attachmentreadA 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 tokenid
attach_filewriteAttach a held file (upload_url), or one the client can read itself as base64target, 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

ToolKindWhat it doesKey parameters
list_bank_accountsreadThe 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_accountreadOne bank account in full: type, currency, balance, account details and latest activityid
list_bank_transactionsreadOne account’s transactions with date, amount, description, unexplained_amount and their explanationsbank_account_id, view, from_date, to_date, updated_since, last_uploaded, page, per_page
get_bank_transactionreadOne bank transaction in full, with its explanationsid
list_bank_feedsreadWhich accounts are connected to their bank, the feed state, and when its authorisation (SCA) expires and must be renewed in FreeAgentnone
upload_bank_statementwriteAdd transactions to an account from statement lines, for example for an account without a bank feedbank_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:

FieldMeaning
dated_on, descriptionRequired
amountRequired. Money out negative, money in positive
fitidThe bank’s own transaction id, if known, so it is not imported twice
transaction_typeCREDIT, 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

ToolKindWhat it doesKey parameters
list_bank_transaction_explanationsreadThe explanations of one account’s transactions: what each payment or receipt was (category, invoice, bill, transfer or user), with VATbank_account_id, marked_for_review_only, from_date, to_date, updated_since, page, per_page
explain_bank_transactionwriteExplain (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_explanationwriteChange only the fields given. marked_for_review: false approves one FreeAgent guessedid, explanation fields, marked_for_review
delete_bank_transaction_explanationwrite, destructiveDelete an explanation, leaving the transaction unexplained againid
approve_explanationswriteApprove 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:

FieldThe money was
categoryAn ordinary payment or receipt, by nominal code such as 285 or 001; see list_categories
paid_invoice_idA customer paying an invoice (or a credit note refunded)
paid_bill_idPaying a supplier’s bill (or a bill refund)
transfer_bank_account_idMoved to or from another of the company’s own accounts
paid_user_idPaid 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_value and dated_on default 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_explanation instead.
  • 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_ids nor approve_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

ToolKindWhat it doesKey parameters
list_categoriesreadFind 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 categoryquery (such as travel, software or 285; leave out for all), group, sub_accounts
  • group: income, cost_of_sales, admin_expenses or general (the balance sheet). Default: all.
  • sub_accounts: true includes sub-accounts such as each bank account (750-x) and each user (900-x).

Reports

ToolKindWhat it doesKey parameters
get_profit_and_lossreadIncome, expenses, operating profit, deductions such as corporation tax and dividends, and retained profit. Default: the current accounting year to datefrom_date, to_date, or accounting_period (a whole year, such as 2025/26)
get_balance_sheetreadCapital 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_balancereadEvery category with its total for a period. A non-zero 999 Suspense or large unexplained balances point at bookkeeping to finishfrom_date, to_date (default today)
get_cashflowreadCash in and out by month, from the bank accounts, with the closing balance. Historic only. Default: the last 12 monthsfrom_date, to_date (default today)
list_accounting_transactionsreadThe general ledger: every posting for a period, optionally for one category, with debit_value (credit negative) and the item it came fromfrom_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

ToolKindWhat it doesKey parameters
list_journal_setsreadManual journals, optionally by tagtag, from_date, to_date, page, per_page
create_journal_setwritePost a manual journal, such as a payroll journal or an accrual. Its entries must balance. Only for someone who knows double entrydated_on, description, entries (2 to 100, below), tag

Each entry of entries:

FieldMeaning
categoryRequired. The category’s nominal code, such as 401 or 814
debit_valueRequired. Debit positive, credit negative, such as 2500.00 or -2500.00. The entries’ debit values must add up to zero
description
user_idFor 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

ToolKindWhat it doesKey parameters
list_tax_returnsreadTax returns of one kind with periods, filing due dates, filing status and payments duekind, user_id
get_tax_returnreadOne return in full by its period end date. A VAT return includes its box 1 to 9 breakdown and paymentskind, period_ends_on (as list_tax_returns gives it), user_id
mark_tax_returnwrite, destructiveRecord 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 accesskind, period_ends_on, action, payment_date, user_id
  • kind is vat, corporation_tax, self_assessment or final_accounts.
  • user_id applies to self_assessment only. 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

ToolKindWhat it doesKey parameters
get_payrollreadPayroll 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 loansyear, period
  • year is the tax year by the year it ends: 2026 for April 2025 to April 2026.
  • period is a pay period, 0 to 11. Leave it out for the year’s periods and payments.

Reviews

ToolKindWhat it doesKey parameters
month_end_checkreadWhat 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 VATfrom_date and to_date, or neither
director_loan_reviewreadEach 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 poundas_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.

ToolKindWhat it doesKey parameters
api_getreadRead 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 addedpath, query
api_requestwrite, destructiveCreate, change or delete through any endpoint with POST, PUT or DELETE, with the body FreeAgent’s API documentation givesmethod, 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

  • path is the endpoint below /v2, such as stock_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_endpoint and approve_app, are refused.
  • Query parameters go in query, never in path.

Query and body

  • query is 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.
  • body is 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.

PromptArgumentsWhat it does
business_snapshotfocusA 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_bookkeepingmonth (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_transactionsbank_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_guessesbank_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_overduetone (friendly, firm or final; default friendly under 30 days overdue, firm after), customerLists 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_invoicerequest (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_timeclient (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_timework (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_expensedetails (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_checkperiod (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_deadlinesmonths (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_closemonth (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_reviewas_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_reviewmonths (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 on permission, stop and say how long to wait on rate_limited, and never guess another id on not_found.
  • Read-only servers. Prompts stay listed when FREEAGENT_READ_ONLY is 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 _:

CommandPrompt
/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

PathContents
.claude-plugin/marketplace.jsonThe marketplace, listing the freeagent plugin from ./plugin
plugin/.claude-plugin/plugin.jsonThe plugin’s name, description and version
plugin/.mcp.jsonThe MCP server: HTTP at ${FREEAGENT_MCP_URL:-http://localhost:7771/freeagent}
plugin/commands/*.mdOne 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 _FILE variables (OAUTH_SIGNING_KEY_FILE, FREEAGENT_CLIENT_SECRET_FILE). Never commit them.
  • Whoever has OAUTH_SIGNING_KEY can 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.

  • /freeagent and /mcp are 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=Lax cookie bound to a random state, 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_KEY to sign everyone out.
  • Clients cannot skip OAuth: there is no static token (MCP_AUTH_TOKEN is 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_PROXIES to the proxy addresses so the client address from X-Forwarded-For is 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 and api_get.
  • Any other tool call returns read_only: the freeagent service is read-only on this server, and is audited as refused.
  • Prompts stay listed; a prompt step that needs a hidden tool tells the model to say so and skip it.
  • It applies on /freeagent and 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}
  • outcome is ok, error or refused (a read-only service); error_kind is the error kind, such as validation (read_only for a refusal), or null on success.
  • subject is the FreeAgent user who signed in, as freeagent:<company subdomain>:user:<id>.
  • Arguments, ids and results are never recorded.
  • Lines go to the audit log target, which stays on at info whatever LOG_LEVEL says, and are appended to AUDIT_LOG_PATH when 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:/audit with AUDIT_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 Authorization header.
  • 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_URL must be https, except a loopback address for tests.
  • Redirects are never followed, and api_get and api_request refuse 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 /healthz returns ok without authentication. It does not contact FreeAgent, so a FreeAgent outage does not get the container restarted.
  • mcp-freeagent --healthcheck connects to 127.0.0.1 on the BIND_ADDR port and exits 0 when /healthz answers. The container image uses it as its HEALTHCHECK, so docker ps shows healthy.

Logs

  • Logs go to stdout, as JSON by default (LOG_FORMAT=pretty for humans).
  • Every tool call logs a tool call line with the tool, outcome and duration, and a failed one a tool failed warning with its error kind. Startup logs freeagent settings (API address and the app’s client id), service enabled and combined endpoint enabled.
  • A sign-in logs signed in to FreeAgent with the person’s subject.
  • LOG_LEVEL takes tracing filters, for example info,mcp_freeagent=debug. Avoid debug or trace for everything (LOG_LEVEL=debug): that also turns on the HTTP libraries’ own debug output, which this server does not cap. Raise only the mcp_freeagent target, or use DEBUG=true.
  • DEBUG=true adds each FreeAgent request’s method, path, status and duration, retries, token requests and tool error messages, without response bodies.
  • DEBUG_UNSAFE_LOG_CONTENT=true adds 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:

MetricWhat it counts
mcp_tool_calls_total, mcp_tool_duration_secondsTool calls by tool and outcome, and their duration
freeagent_requests_total, freeagent_request_duration_secondsFreeAgent API requests by endpoint label and status class, and their duration
freeagent_rate_limited_totalAPI requests FreeAgent refused with 429
freeagent_token_requests_totalRequests to FreeAgent’s token endpoint by grant (authorization_code or refresh_token) and HTTP status
freeagent_refresh_token_rotations_totalRefreshes where FreeAgent handed out a new refresh token
freeagent_token_store_errors_totalFailed writes of FREEAGENT_TOKEN_STORE
oauth_requests_total, oauth_login_failures_totalRequests to the server’s own OAuth endpoints, and failed sign-ins
http_requests_totalHTTP 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 the FREEAGENT_TOKEN_STORE volume.
  • Binary: replace the file and restart.
  • Connectors stay signed in across upgrades and restarts as long as OAUTH_SIGNING_KEY, PUBLIC_URL, FREEAGENT_CLIENT_ID and 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:

MessageFix
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 bytesUse openssl rand -hex 32
FREEAGENT_CLIENT_ID is required, FREEAGENT_CLIENT_SECRET is requiredSet 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-01Use a date, or leave it unset
MCP_AUTH_TOKEN cannot be used when people sign in with their own FreeAgent accountRemove 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>/callback with the app, scheme and port included, for example http://localhost:7771/callback for local use. PUBLIC_URL must be exactly the address the server is reached at.
  • Wrong environment. A sandbox company needs FREEAGENT_ENVIRONMENT=sandbox, and the live one production (the default).

The sign-in page reports a problem

The page saysCause and fix
FreeAgent refused this server's app credentials; ask the server's operator to check themFREEAGENT_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 minuteFreeAgent’s rate limit. Wait a minute
FreeAgent granted no refresh tokenFreeAgent’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 FreeAgentThe 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:8443 with No TLS Verify on.
  • PUBLIC_URL must 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 without FREEAGENT_TOKEN_STORE. Reconnect the connector, or run /mcp in Claude Code.
  • The client gets 401 everywhere: OAUTH_SIGNING_KEY or PUBLIC_URL changed, 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_URL or FREEAGENT_CLIENT_ID ends every sign-in.
  • 90 days after signing in, every grant ends and the person signs in again.
  • A token for /freeagent is 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:

ErrorWhat 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 secondsWait 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 APIFREEAGENT_API_URL points somewhere else
read_only: the freeagent service is read-only on this serverFREEAGENT_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_PATH is 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

CrateRole
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-booksThe 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-freeagentThe 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 url gets an id beside it, so models spend fewer tokens and can pass ids back directly. Attachments lose their signed download links (content_src and its thumbnails, with expires_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 a too_large error that says what per_page fits.
  • 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 develop as feature/<name>, bugfix/<name> or hotfix/<name>, and open the pull request against develop.
  • 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/* and bugfix/* branches merged into develop by pull request.
  • Every merge into develop that touches the server (crates/, Cargo.toml, Cargo.lock or the Dockerfile) publishes a pre-release vX.Y.Z-dev.N: a GitHub pre-release and image tags X.Y.Z-dev.N and develop.
  • A pull request from develop into main publishes a release vX.Y.Z when merged: image tags X.Y.Z, X.Y, X and latest, binaries for Linux x86_64 and arm64 and macOS arm64 with checksums, and this documentation site.
  • The version bump comes from the develop to main pull request: a major, minor or patch label, otherwise [major], [minor] or [patch] in its title, otherwise patch.
  • Pull requests into main must come from develop in 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: write and pages: 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-freeagent package visibility to public under Packages for anonymous pulls.