API Docs

AI Toolkit

Pricing

$0.25

API Docs

AI Toolkit

Changelog

Pricing

$0.25

All posts
Guides

Build a contract-drafting agent that fills a DOCX template and sends it

A design for an AI agent that turns a conversation into contract terms, merges them into a Word template and sends the result for signature, with a person approving every live send.

A common request for AI features goes like this: a user describes a deal in a sentence or two, and the product produces the contract and sends it for signature. “Send Acme a consulting agreement, 40 hours a month at 120 dollars an hour, starting January 5th, signed by their COO.” The language model is good at the first half of that job. The second half, producing a correct document and getting it signed, is where the design needs care.

This post describes an agent that splits the work cleanly. The model extracts terms. Your code validates them and merges them into a Word template that your legal team owns. SignatureAPI generates the document and runs the signing. A person approves before anything reaches a real signer.

Why the model should not write the contract

The tempting design is to let the model draft the full contract text and send it as a PDF. It demos well. It also means every contract is a new document that nobody reviewed, with wording that can drift between runs, and with no clean way to tell which clauses a lawyer approved.

A template avoids this. The legal text lives in a DOCX file that a person wrote and reviewed. The model’s output is a small, typed object: names, dates, amounts and a few choices. That object is easy to validate, easy to log and easy to show a person before sending.

The template

SignatureAPI merges DOCX templates with data you send in the envelope request. Fields use double curly braces, and nested values use dot notation:

This Consulting Agreement is entered into by {{client.name}} and {{consultant.name}}.
The Consultant will provide up to {{hoursPerMonth}} hours of services per month
at a rate of {{hourlyRate}} per hour, starting on {{startDate}}.

{{if mediation}}
Any dispute shall first be submitted to mediation.
{{else}}
Any dispute shall be settled by arbitration.
{{endif}}

Client: [[client_signature]]          Consultant: [[consultant_signature]]

Two kinds of markers share the file. {{field}} tags inject content before signing. [[place_key]] placeholders mark where each recipient signs. Keys used inside an {{if}} condition should be camelCase or a single word, because an underscore in a nested condition key causes a template error.

Save the file from Microsoft Word. DOCX files from other editors may not parse correctly. Store it in your Dashboard library or anywhere with a stable URL.

The tool the model calls

Give the model one tool, with a schema that mirrors the template’s fields. Tools are usually described with JSON Schema; the wrapper around the schema differs between model APIs, so adapt the outer keys to yours:

JSON
{
  "name": "draft_consulting_agreement",
  "description": "Prepare a consulting agreement from the approved template. Does not send it.",
  "input_schema": {
    "type": "object",
    "required": ["client", "consultant", "hoursPerMonth", "hourlyRate", "startDate", "mediation"],
    "properties": {
      "client": {
        "type": "object",
        "required": ["name", "signerName", "signerEmail"],
        "properties": {
          "name": { "type": "string" },
          "signerName": { "type": "string" },
          "signerEmail": { "type": "string", "format": "email" }
        }
      },
      "consultant": {
        "type": "object",
        "required": ["name", "signerName", "signerEmail"],
        "properties": {
          "name": { "type": "string" },
          "signerName": { "type": "string" },
          "signerEmail": { "type": "string", "format": "email" }
        }
      },
      "hoursPerMonth": { "type": "integer", "minimum": 1, "maximum": 200 },
      "hourlyRate": { "type": "string", "description": "Amount with currency, for example USD 120" },
      "startDate": { "type": "string", "format": "date" },
      "mediation": { "type": "boolean" }
    }
  }
}

The description says “does not send it” on purpose. Drafting and sending are separate steps, and only your code moves from one to the other.

From tool call to envelope

When the model calls the tool, your handler validates the input against the same schema, then builds the envelope. The template’s [[...]] placeholders become places, and the validated object becomes the document’s data.

Python
def build_envelope(terms: dict, template_url: str, draft_id: str) -> dict:
    return {
        "title": f"Consulting Agreement: {terms['client']['name']}",
        "metadata": {"source": "contract_agent", "draft_id": draft_id},
        "documents": [
            {
                "url": template_url,
                "format": "docx",
                "data": {
                    "client": {"name": terms["client"]["name"]},
                    "consultant": {"name": terms["consultant"]["name"]},
                    "hoursPerMonth": terms["hoursPerMonth"],
                    "hourlyRate": terms["hourlyRate"],
                    "startDate": terms["startDate"],
                    "mediation": terms["mediation"],
                },
                "places": [
                    {"key": "client_signature", "type": "signature", "recipient_key": "client"},
                    {"key": "consultant_signature", "type": "signature", "recipient_key": "consultant"},
                ],
            }
        ],
        "recipients": [
            {"key": "client", "type": "signer",
             "name": terms["client"]["signerName"], "email": terms["client"]["signerEmail"]},
            {"key": "consultant", "type": "signer",
             "name": terms["consultant"]["signerName"], "email": terms["consultant"]["signerEmail"]},
        ],
    }

Send that body to POST /v1/envelopes with your API key, from your server. The key never goes into the model’s context.

Preview in test mode, send in live mode

The safest flow sends every draft as a test envelope first. Test envelopes send no email to recipients, carry a watermark and are free. Once the test envelope is in progress, its snapshot_url points to a PDF of the merged document. Your app shows that PDF next to the extracted terms and asks the user for approval. Cancel the test envelope afterwards.

Only when the user approves does your code send the same body with the live key. The model never chooses the mode. A wrong email address or a misheard amount is caught on a watermarked draft instead of in a client’s inbox.

Two details make this loop robust:

  • Validate before every send. If the model fills a field with something that fails the schema, return the validation error to the model as the tool result and let it ask the user.
  • Put your own identifiers in metadata. They come back in every webhook payload, so the deliverable.generated event can update the right draft and store the signed PDF.

If your agent already speaks MCP

If the agent runs in an MCP client, such as a coding agent or a chat assistant, you can skip the REST code during prototyping. The SignatureAPI MCP server exposes tools such as create_envelope, inspect_upload and get_deliverables, and its tools default to test mode. inspect_upload reports the {{field}} tags and [[placeholder]] keys it found in a DOCX, which is a quick way to check that a template matches your schema before the first send. The tools page is the current catalog.

For a product feature, keep the REST path described above. It puts the validation, the approval step and the live key in code you control.

What to watch

Template drift is the main long-term risk. When legal changes the template, the schema and the template can disagree. Before you switch to a new version, compare its fields with your schema, for example with inspect_upload, and send one test draft through the preview step yourself.

The document templates reference covers conditionals, repeating regions and dynamic tables in more depth.

START FOR FREE

Ready to get started?
Create an account instantly, no credit card required.

Get Started