How to integrate Freeagent MCP with Pydantic AI

Connect Pydantic AI to Freeagent MCP. List overdue invoices for this month, create a new expense for office supplies, and more using natural language, with authentication handled for you.

Freeagent logoFreeagent
Oauth2

Freeagent is a cloud-based accounting platform designed for freelancers and small businesses. It simplifies bookkeeping, invoicing, and expense management in one place.

107 Tools

Introduction

This guide walks you through connecting Freeagent to Pydantic AI using the Composio tool router. By the end, you'll have a working Freeagent agent that can create invoices and estimates, track expenses and timeslips, manage contacts and projects, and pull P&L and balance sheet reports through natural language commands.

This guide will help you understand how to give your Pydantic AI agent real control over a Freeagent account through Composio's Freeagent MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

For exact tool slugs and parameter tables, see the tool catalog in the Composio docs.

Also integrate Freeagent with

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Freeagent
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Freeagent workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

What is the Freeagent MCP server, and what's possible with it?

The Freeagent MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Freeagent account. It provides structured and secure access to your accounting records, so your agent can create invoices, record timeslips, review expenses, monitor cash flow, and track tax deadlines on your behalf.

  • Invoices, estimates, and credit notes: Have your agent create invoices, estimates, and credit notes, convert estimates into invoices, or convert eligible invoices into credit notes.
  • Financial reporting: Let the agent retrieve cash flow, profit and loss, trial balance, balance sheet, opening balance, and accounting transaction details for your business.
  • Expenses, bills, and banking: Direct your agent to list or update expenses, create bills with attachments, review bills and bank transactions, or create and list bank accounts.
  • Contacts, projects, and time tracking: Instruct your agent to create contacts and projects, review existing records, and add timeslips for completed work.
  • Tax and VAT planning: Have your agent list VAT returns and check your company tax timeline for upcoming events and deadlines.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Freeagent
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs
5

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Freeagent
  • MCPServerStreamableHTTP connects to the Freeagent MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant
6

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Freeagent
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["freeagent"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Freeagent tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
7

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
freeagent_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[freeagent_mcp],
    instructions=(
        "You are a Freeagent assistant. Use Freeagent tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Freeagent endpoint
  • The agent uses GPT-5 to interpret user commands and perform Freeagent operations
  • The instructions field defines the agent's role and behavior
8

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Freeagent.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Freeagent API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns
9

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Freeagent and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Freeagent
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["freeagent"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    freeagent_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[freeagent_mcp],
        instructions=(
            "You are a Freeagent assistant. Use Freeagent tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Freeagent.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Freeagent through Composio's Tool Router. With this setup, your agent can perform real Freeagent actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Freeagent for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.
TOOLS

Supported Tools

Every Freeagent action and event your agent gets out of the box.

Cashflow summary for a date range

Tool to retrieve cashflow summary for a given date range from FreeAgent.

Get Company Details

Tool to retrieve company details from FreeAgent.

Create a Journal Set

Tool to create a journal set in FreeAgent.

Create Sales Tax Period

Tool to create a sales tax period in FreeAgent.

Create Task Under Project

Tool to create a task under a specific project in FreeAgent.

Create A Timeslip

Tool to create a new timeslip in FreeAgent.

Create a User

Tool to create a new user in FreeAgent.

Create Bank Account

Tool to create a bank account in FreeAgent.

Create Bill with Attachment

Tool to create a bill with optional attachment in FreeAgent.

Create Category

Tool to create a custom category in FreeAgent.

Create Contact

Tool to create a new contact in FreeAgent.

Create Credit Note

Tool to create a credit note in FreeAgent.

Create Credit Note Reconciliation

Tool to create a credit note reconciliation in FreeAgent.

Create Estimate

Tool to create a new estimate in FreeAgent.

Create Estimate Item

Tool to create an estimate item in FreeAgent.

Duplicate Estimate

Tool to duplicate an existing estimate in FreeAgent.

Send Estimate Email

Tool to email an estimate in FreeAgent.

Create Expense

Create a single standard or mileage expense in FreeAgent.

Create Invoice

Tool to create an invoice in FreeAgent.

Create Invoice Item

Tool to create an invoice item in FreeAgent.

Duplicate Invoice

Tool to duplicate an existing invoice in FreeAgent.

Create Note

Tool to create a note for a contact or project in FreeAgent.

Create Price List Item

Tool to create a price list item in FreeAgent.

Create Project

Tool to create a project in FreeAgent.

Delete Attachment

Permanently delete a FreeAgent attachment by its numeric ID.

Delete Bank Transaction Explanation

Tool to delete a bank transaction explanation in FreeAgent.

Delete Bill

Delete a bill by its FreeAgent identifier.

Delete Contact

Permanently delete a FreeAgent contact by ID.

Delete Estimate Item

Delete one line item from a FreeAgent estimate.

Delete Estimates Default Additional Text

Tool to delete default additional text for estimates in FreeAgent.

Delete Expense

Delete an expense by its FreeAgent identifier.

Delete Invoice

Permanently delete a FreeAgent invoice by ID.

Delete Journal Set

Delete a tagged FreeAgent journal set by its numeric ID.

Delete Note

Tool to delete a note by its ID.

Get Attachment

Retrieve any attachment's metadata and expiring content URLs by numeric ID.

Get Bill

Retrieve one FreeAgent bill by ID, including its line items and attachment metadata.

Get Category

Retrieve one FreeAgent accounting category by nominal code.

Get Contact

Retrieve one FreeAgent contact by its numeric ID.

Get Credit Note

Retrieve one FreeAgent credit note by its numeric ID, including line items.

Get Estimate

Retrieve one FreeAgent estimate by ID, including its estimate items.

Get Estimate Item

Retrieve one FreeAgent estimate line item by ID.

Get Expense

Retrieve one FreeAgent expense by ID, including its receipt attachment.

Get Invoice

Retrieve one FreeAgent invoice by its numeric ID, including line items.

Get Invoice Timeline

Tool to retrieve invoice timeline showing chronological record of invoice-related events.

Get Journal Set

Retrieve one FreeAgent journal set and its journal entries by numeric ID.

Get Mileage Settings

Tool to retrieve mileage settings including engine type/size options and reimbursement rates.

Get Opening Balances

Tool to retrieve the Opening Balances journal set for a company.

Get Personal Profile

Tool to retrieve the authenticated user's personal profile from FreeAgent.

Get Price List Item

Retrieve one FreeAgent price-list item by ID.

Get Project

Retrieve one FreeAgent project by its numeric ID.

Get the Opening Balances

Tool to retrieve the opening balances from the trial balance summary.

Get the P&L summary

Tool to retrieve the Profit and Loss summary for a specified period from FreeAgent.

Get Trial Balance Summary

Tool to get the trial balance summary from FreeAgent.

Get Balance Sheet

Tool to retrieve the balance sheet for a FreeAgent account.

Get Opening Balances

Tool to retrieve opening balances for the balance sheet from FreeAgent.

List Accounting Transactions

List a page of FreeAgent accounting transactions, optionally filtered by date range or nominal code.

List All CIS Bands

Tool to list all CIS (Construction Industry Scheme) bands for a company.

List All Expenses

List a page of FreeAgent expenses, optionally filtered by view type, date range, project, or last update timestamp.

List All Price List Items

List a page of FreeAgent price list items, optionally sorted by creation date, code, or update date.

List All Properties

Tool to list all properties in FreeAgent.

List All Recurring Invoices

Tool to retrieve a list of recurring invoices from FreeAgent.

List All Sales Tax Periods

Tool to list all sales tax periods for a company in FreeAgent.

List All Stock Items

List a page of FreeAgent stock items, with optional sorting by creation date, description, or update date and pagination controls.

List All Tasks

List a page of FreeAgent tasks with optional filtering by status, project, or update date, sorting, and pagination controls.

List All Timeslips

List a page of FreeAgent timeslips, with optional filtering by date range, user, project, task, billing status, or last update timestamp and pagination controls.

List All Users

Tool to list users in FreeAgent.

List Bank Accounts

Tool to list bank accounts in FreeAgent.

List Bank Feeds

Tool to list all bank feeds for a company.

List Bank Transaction Explanation Attachments

List file attachments for a FreeAgent bank transaction explanation.

List Bank Transactions

List a page of bank transactions for a specified FreeAgent bank account.

List Bills

Tool to retrieve a list of bills from FreeAgent.

List Business Categories

Tool to retrieve all available business categories from FreeAgent.

List Categories

Tool to retrieve all categories for the current FreeAgent company.

List Contacts

Tool to list contacts in FreeAgent.

List Credit Note Reconciliations

List a page of FreeAgent credit note reconciliations, optionally filtered by update timestamp or date range.

List Credit Notes

List FreeAgent credit notes with optional filtering by contact, project, status, or update time.

List EC MOSS Sales Tax Rates

Tool to retrieve EC VAT MOSS sales tax rates for a specific EU country and date.

List Estimates

Tool to list estimates in FreeAgent.

Get Default Estimates Additional Text

Tool to retrieve the default additional text for estimates.

List Final Accounts Reports

Tool to list final accounts reports for a company in FreeAgent.

List Hire Purchases

Tool to retrieve all hire purchases for the authorized FreeAgent account.

List Invoices

List ordinary FreeAgent invoices with filters and optional nested line items.

Get Default Additional Text

Tool to get the default additional text shown on all invoices.

List Notes

List notes for a specific contact or project, with pagination.

List Projects

Tool to list projects in FreeAgent.

List VAT Returns

Tool to list VAT returns for a company in FreeAgent.

Mark Invoice as Draft

Return a sent FreeAgent invoice to draft status.

Mark Invoice as Sent

Mark a draft invoice as sent without emailing it, or reopen a cancelled one.

Send Invoice Email

Email an existing invoice using explicit fields or an account template.

Show Tax Timeline

Tool to retrieve the company's tax timeline showing upcoming tax events and deadlines.

Update Bank Transaction Explanation

Tool to update a bank transaction explanation in FreeAgent.

Update Bill

Update a bill and create, update, or delete its line items.

Update Contact

Update mutable identity, contact, address, invoicing, and CIS fields.

Update Estimate Item

Update editable fields on an existing FreeAgent estimate item.

Update Estimates Default Additional Text

Tool to update the default additional text for estimates in FreeAgent.

Convert Estimate to Invoice

Tool to convert an estimate to an invoice in FreeAgent.

Update Expense

Tool to update an existing expense in FreeAgent.

Update Invoice

Update an invoice, including adding, changing, or deleting its line items.

Update Invoice Item

Update an existing invoice line item by its direct identifier.

Update Invoices Default Additional Text

Tool to update the default additional text shown on all invoices.

Convert Invoice to Credit Note

Tool to convert a draft negative invoice to a credit note in FreeAgent.

Update a Journal Set

Update a FreeAgent journal set's description, date, tag, or entries, including adding, modifying, or removing entries.

Update Note

Tool to update an existing note in FreeAgent.

Update Price List Item

Tool to update a price list item in FreeAgent.

Update Project

Update selected attributes of an existing FreeAgent project.

Update Personal Profile

Tool to update the authenticated user's personal profile in FreeAgent.

Upload a Bank Statement

Tool to upload a bank statement to FreeAgent.

FAQ

Frequently asked questions

Start with Freeagent.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Freeagent tool your agent needs.Free to start.

Start building