Build an agent with MCP

Run a read-only Python client, propose an entity-specific bill rule, handle the approval workflow and verify the exact version saved.

Give your assistant one job it can do well. In this example it checks a supplier invoice against the books and gives AP a short review. You can keep the procedure in a Cowork project, package it as a ChatGPT plugin, or run it in your own Python integration.

Where you want to workStart here
Your AP team reviews invoices in ClaudeSet up a Cowork project
Your team wants a reusable procedure in ChatGPTCreate a ChatGPT plugin
Your application needs to call Arfiti directlyRun a read-only Python client

Write the review instructions

Start with a supplier invoice you have already posted in a practice entity. Save the instructions below in your chosen client. Replace the bracketed text with your company and entity. The purchase-order check is an example of a rule your AP team might choose.

You help AP review supplier invoices for [company] in [legal entity]. At the start of each task, read the company and entity from Arfiti and confirm they match. Look up the invoice by supplier and invoice reference. If several records match, ask me which one to review. Show the saved bill number, currency, gross total and amount due. For a hardware invoice, flag a missing purchase order for AP. For this review, use read-only tools and leave the bill as you found it.

Set up a Cowork project

  1. Create a Cowork project for the company, name it Supplier bill review and save the review instructions in its project instructions. A new task in this project can reuse them. Cowork projects
  2. Connect Arfiti and sign in with the account for that entity. If you want Arfiti’s bill-handling procedure as well, install the Arfiti plugin from the Arfiti marketplace. Connection steps · Plugin installation
  3. Start a task in the project and ask, “Which company and legal entity can you read?” Once they match, give Cowork the supplier and reference for the practice invoice. Check the result

Create a ChatGPT plugin

  1. In a workspace that allows custom MCP connections, connect Arfiti and verify the company and entity. If you want general accounting procedures, you can also select the Accounting plugin. The Arfiti connection supplies access to the records. ChatGPT quick start
  2. For a personal procedure, save the review instructions in a ChatGPT project's instructions and use that project for each review. To package the procedure for colleagues, open Plugins, select Add (+) and use Plugin Creator where available. ChatGPT projects · Create a ChatGPT plugin
  3. Ask Plugin Creator, “Create a Supplier Bill Review plugin with a skill that follows these instructions. Use the Arfiti connection to look up the saved bill.” Include your review instructions. Check the skill it creates, the tools it requests and the expected output. Install the plugin if prompted.
  4. Start a fresh chat, select your plugin and Arfiti connection, and provide the practice invoice reference. Before sharing the plugin, try it with a colleague who has access to the practice entity. Each person signs in with their own authorized account.

Test your assistant

Ask, “Review invoice [reference] from [supplier] in [entity].” Compare the returned bill number, gross total and amount due with the saved bill. A partly paid bill makes a useful test because its gross total and outstanding balance differ.

Then try a reference you know is absent. The assistant should report that it found no matching bill and ask for the reference. If it invents an amount or uses another entity, correct the instructions or connection and repeat both checks in a fresh task. Once the review works, you can extend it to prepare a posting for approval. Supplier invoice walkthrough · Approval workflows

A project or plugin runs when you invoke it in the client. If you want recurring processing, decide which client or service will start each run and check whether an existing agent already handles those bills. Agent management

Build a bill assistant

Suppose your team wants its assistant to ask Accounts Payable about a missing purchase order before posting a hardware bill. First connect a client that can read one company's rules. Then use a separate, authorized workflow to propose a change to those rules. An agent that only processes bills can stop after the read-only example.

You will need Python 3.11 or later, the IDs of your Arfiti organization and legal entity, and a read-only Arfiti key scoped to that entity. In Configuration → Organizations you can find the organization ID and MCP URL. In Configuration → Entities you can find the entity. For a client acting as a signed-in person, use its OAuth connection instead. API key setup · Access and sign-in

Run a read-only client

Install the SDK in your project environment. This example uses the official Python SDK's 1.26 client API. Python MCP SDK

python -m pip install "mcp==1.26.0"

Supply ARFITI_API_KEY from your secret manager. Set ARFITI_ORGANIZATION_ID and ARFITI_ENTITY_ID to the numeric IDs you expect. Save the following as read_bill_rules.py and run python read_bill_rules.py. It opens a session pinned to the organization, discovers tools and reads the selected entity and its rules. The script prints company and entity names and a rule count.

import asyncio
import json
import os

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client


async def call(session, tool, **arguments):
    reply = await session.call_tool(tool, arguments=arguments)
    if reply.isError:
        raise RuntimeError(f"{tool} returned an MCP tool error")

    value = reply.structuredContent
    if value is None:
        blocks = [block.text for block in reply.content if block.type == "text"]
        if len(blocks) != 1:
            raise ValueError(f"Expected a single JSON result for {tool}")
        value = json.loads(blocks[0])
    if isinstance(value, dict) and set(value) == {"result"}:
        value = value["result"]
    if isinstance(value, str):
        value = json.loads(value)
    if not isinstance(value, dict):
        raise ValueError(f"Unexpected result type from {tool}")
    return value


def checked(result):
    if result.get("success") is False or result.get("error"):
        raise RuntimeError(result.get("error") or result.get("message") or "Read failed")
    return result


async def inspect_company(session, org_id, entity_id):
    await session.initialize()
    tools = set()
    cursor = None
    while True:
        page = await session.list_tools(cursor=cursor)
        tools.update(tool.name for tool in page.tools)
        cursor = page.nextCursor
        if not cursor:
            break
    required = {"get_organization", "get_entity", "query"}
    if missing := required - tools:
        raise RuntimeError(f"Connection lacks expected tools: {sorted(missing)}")

    org = checked(await call(session, "get_organization", action="get_info"))
    if int(org["id"]) != org_id:
        raise RuntimeError("Wrong organization")
    result = checked(await call(session, "get_entity", entity_type="legal_entity", id=entity_id))
    entity = result["entity"]
    if int(entity["id"]) != entity_id or not entity["is_active"]:
        raise RuntimeError("Expected an active legal entity")
    rules = checked(await call(
        session, "query", entity_type="agent_rules",
        filters={"agent_type": "bill_processor", "legal_entity_id": entity_id},
    ))
    if any(row["status"] != "ok" for row in rules["results"]):
        raise RuntimeError("A stored rule needs review")
    print(f"{org['name']} / {entity['entity_name']} ({entity['functional_currency']})")
    print(f"Applicable bill rule sets: {rules['count']}")


async def main():
    org_id = int(os.environ["ARFITI_ORGANIZATION_ID"])
    entity_id = int(os.environ["ARFITI_ENTITY_ID"])
    url = f"https://mcp.arfiti.com/streamable/mcp?org={org_id}"
    headers = {"X-API-Key": os.environ["ARFITI_API_KEY"]}
    async with httpx.AsyncClient(headers=headers, timeout=30.0) as http:
        async with streamable_http_client(url, http_client=http) as (read, write, _):
            async with ClientSession(read, write) as session:
                await inspect_company(session, org_id, entity_id)


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

An HTTP sign-in failure, an MCP tool error and an Arfiti refusal are different results. A valid MCP response can contain an Arfiti object with success: false or error. Keep the raw response in protected diagnostics when investigating a failed read. Credentials, rule text and complete vendor documents do not belong in ordinary application logs.

A successful count of zero means there are no applicable saved rules for this query. For a bill task, give the assistant the returned handling and prompt_block as customer guidance. Arfiti resolves rules for all agents and the bill agent at organization and entity scope. If the read was refused or the entity was wrong, stop the task and correct access.

Propose a rule for one entity

Suppose AP agrees to this instruction: “Ask AP for the purchase order reference before proposing a hardware bill that has none.” First inspect the current rule set for the bill agent at that exact entity scope. Saving content.text sets the entire text at that level. Merge with any rules the team wants to keep and show the full proposed wording for review.

Use a write-capable identity authorized for this action and a separate session from the read-only example. An owner, admin or person with accounting close permission can decide a policy change. Someone with accounting write permission can propose one. Arfiti requires a human decision on an agent's proposal, and the organization can impose additional approval steps. Calling a tool from an OAuth client as a human uses that person's identity. Company rules for agents

The following functions use the call and checked helpers above. Call them from an initialized session. In the integration's database, save one request key with the intended organization, entity, operation and reviewed payload before sending it. Load the same key and same payload after a restart.

async def propose_bill_rule(session, entity_id, reviewed_text, request_key):
    payload = {
        "namespace": "agent.rules",
        "section": "bill_processor",
        "legal_entity_id": entity_id,
        "content": {"text": reviewed_text},
        "reason": "AP requested a purchase order check for hardware bills.",
    }
    encoded = json.dumps(payload)
    schema = checked(await call(
        session, "get_submissions", action="schema",
        object_type="policy", operation="save", payload=encoded,
    ))
    missing = {field["field"] for field in schema["required_fields"]} - payload.keys()
    if missing:
        raise ValueError(f"Company requires additional fields: {sorted(missing)}")

    return await call(
        session, "submit", object_type="policy", operation="save",
        data=encoded, idempotency_key=request_key,
    )

data is JSON text in the MCP tool arguments. Keep legal_entity_id in the payload: omitting it proposes an organization-wide rule. A successful preview using validate_only=True, where supported, writes nothing and gives no assurance that a later execution will complete.

Interpret the receipt before acting again

Save the returned workflow ID and status alongside the request key. Some operations return both workflow_status and a separate record status, such as a document that remains a draft after its creation workflow completed.

What you receiveWhat the client should do
status is pending or in_progressThe submission exists. Follow the workflow. A pending response may say success: true before any rule is saved.
requires_confirmation: true with confirmation_task_idShow the submitter the named task and the actual proposed wording. Wait for a decision.
success: true and policy_version_idRead that version and the rules currently in force.
refused: true and effect_outcome: "no_effect"Show the reason and keep the refusal. If the user corrects the input, record a new intent and key.
A timeout after sending, posting_unknown, or no conclusive receiptKeep the original key. Inspect the workflow history and saved rules. Use the same key and unchanged payload to recover a receipt. Escalate an unresolved outcome before another write.
idempotent_replay: trueThe request was recognized. Examine the returned operation result and any original_workflow_id. A replay of an earlier pending response still calls for a status check.
error: "idempotency_key_reused"The key was used for a different operation or payload. Reconcile the original intent before assigning a key to the changed one.

A rejected task ends that approval path. A transport exception only tells you that the client lost its answer. Write identities are retained across uncertain execution, so waiting overnight is no reason to start the same write again. A distinct business action needs its own request identity.

Follow the approval and verify what was saved

  1. Use get_submissions(action="history", workflow_id=workflow_id) as the submitter. The history includes status, submitted_at, completed_at and a sequence of recorded actions. Poll this read with backoff while the workflow is pending.
  2. The assigned reviewer can use get_submissions(action="my_tasks", status="pending") and then get_submissions(action="task_details", task_id=task_id). Display the proposal and ask for a decision in the reviewer’s own session.
  3. After the reviewer chooses, that session can call manage_submissions(action="decide", task_id=task_id, decision="approve", notes=review_note). Available decisions also include reject and request_changes. Where the task supplies a payload hash, pass it as expected_payload_hash so the decision refers to the wording the person reviewed.
  4. Read the saved version by ID. If a completed approval supplied only a workflow reference, inspect the current rules and their version history to identify the saved version. A later edit can supersede an earlier valid decision. Treat a missing or ambiguous version as unresolved.
async def verify_bill_rule(session, entity_id, version_id, reviewed_text):
    row = checked(await call(
        session, "get_entity", entity_type="agent_rules", id=version_id,
    ))["entity"]
    if (row["id"] != version_id or row["status"] != "ok" or row["kind"] != "set"
            or row["agent_type"] != "bill_processor"
            or row["legal_entity_id"] != entity_id or row["rules"] != reviewed_text):
        raise ValueError("Saved version differs from the approved rule")
    current = checked(await call(
        session, "query", entity_type="agent_rules",
        filters={"agent_type": "bill_processor", "legal_entity_id": entity_id},
    ))
    return any(rule["id"] == row["id"] and rule["status"] == "ok"
               for rule in current["results"])

A true result confirms that particular version is in force for the chosen entity.

Apply the rule to a supplier bill

For a hardware bill without a purchase order, ask AP for the missing reference and keep the source document with the task. Once the reviewer resolves it, look up the vendor, posting account and tax code for this entity. Search for an existing bill with the same vendor and invoice reference before proposing a posting.

Use get_submissions with action="schema", object_type="transaction", operation="post" and a JSON-text payload containing the proposed transaction_type_code="AP_INVOICE" and legal_entity_id. Check the returned required_fields, resolved_line_required_fields and any workflow_requirements. The bill header carries the vendor ID, dates, vendor reference and currency. A typical item line contains a quantity, unit price, expense account or item, and the tax code agreed for that purchase. The supplied payload lets Arfiti resolve requirements for the selected transaction type and organization.

Show the proposed supplier, net, tax, total and posting date to the reviewer. An authorized posting uses the same submit pattern with object_type="transaction", operation="post", the completed JSON-text payload and a request key for this bill. After execution, read the saved transaction and compare the supplier reference, entity, gross total and payable with the source. Retain the invoice number, workflow ID and original attachment reference so a colleague can trace the posting. Supplier invoice walkthrough

Observe events and managed runs

A bill.upload event addressed to bill_processor can start a managed session. A bank_statement.manual_import event can address the bank agent. Scheduled work can arrive as schedule.triggered. An event can also wait or be ignored. Each event, managed run, approval workflow and resulting financial record has its own ID.

For a monitoring integration, poll query(entity_type="managed_agent_run", filters={"agent_type": "bill_processor", "legal_entity_id": entity_id}, limit=10). Each result includes a run id, agent_event_id, trigger, state and legal_entity_id. The trigger describes how the run started, for example event or schedule. Where available and authorized, follow agent_event_id with get_entity(entity_type="agent_event", id=event_id) and inspect the run with get_entity(entity_type="managed_agent_run", id=run_id). Use pagination and deduplicate observed runs by ID. Reading the list gives you a snapshot. It does not subscribe your client to future events.

Your own agent can submit supported operations directly. If it will replace a managed agent that processes recurring inputs, inspect the definition's config.runtime, its active runs, scheduled triggers and pending work before changing ownership. An authorized operator can use agent_definition.set_runtime to remove managed dispatch and verify the built-in worker remains disabled. Later work should have one owner per input. Agent setup and handoff · Workflow results and recovery