OpenAI Agents SDK + Signbee: Handoffs, Guardrails & Certified E-Signatures (2026)
Giving an LLM tool access to send legally binding contracts requires strict architectural isolation. Learn how to orchestrate multi-agent handoffs, tripwire guardrails, and cryptographic SHA-256 e-signatures using the official OpenAI Agents SDK and Signbee.
Quick Answer (TL;DR)
Multi-Agent Legal Execution Blueprint • Python & TypeScript SDKs
To build a safe autonomous contracting pipeline with the OpenAI Agents SDK (openai-agents in Python or @openai/agents in TypeScript), separate commercial negotiation from legal execution using Agent Handoffs. A front-line Sales/Triage Agent gathers deal terms without holding any external dispatch tools, then executes a typed handoff() to a specialized Legal Closing Agent protected by @input_guardrail and @output_guardrail tripwires. Once compliance checks pass, the Closing Agent invokes Signbee via POST https://signb.ee/api/v1/send or MCPServerStdio("npx -y signbee-mcp") to compile CommonMark Markdown into a SHA-256 certified PDF ceremony.
1. The Multi-Agent Imperative: Why Single-Prompt Chatbots Fail at Contract Execution
When engineering teams first experiment with agentic workflows, the most common anti-pattern is building a monolithic “God Agent”—a single LLM instance equipped with a 4,000-word system prompt and 25 simultaneous tool definitions spanning CRM lookup, pricing discount calculation, email dispatch, and legal contract execution.
In production, monolithic agents suffer from three severe reliability hazards when dealing with consequential actions like electronic signatures:
- Premature Tool Invocation: A conversational agent that holds the
send_contracttool in its active toolset during early discovery may misinterpret an exploratory user message (such as “What would a contract for 50 seats look like?”) as an instruction to immediately dispatch an envelope to the client. - Prompt Injection & Unauthorized Concession Leakage: If an external prospect interacts directly with an agent that possesses live signing credentials, adversarial prompt manipulation can coax the model into inserting uncapped indemnity clauses or unauthorized 80% price discounts directly into the contract payload.
- Coordinate Hallucination in Legacy APIs: As we detailed in our analysis of the best e-signature APIs for developers in 2026 and DocuSign API pricing explained, traditional e-signature APIs demand binary PDF uploads and floating-point pixel coordinates (
x, y, pageNumber) that language models cannot reason about.
Combining the OpenAI Agents SDK with Signbee solves all three problems cleanly. The OpenAI Agents SDK provides structural primitives for privilege separation via Handoffs and parallel validation via Guardrails, while Signbee provides a zero-coordinate JSON and MCP execution layer that compiles CommonMark Markdown or PDFs into SHA-256 certified agreements.
2. Core Primitives of the OpenAI Agents SDK Mapped to Signbee
Evolving from OpenAI's experimental Swarm framework into a production-hardened SDK across both Python (pip install openai-agents) and TypeScript (npm install @openai/agents), the OpenAI Agents SDK centers on five composable primitives. Here is how each primitive maps to an enterprise contract execution pipeline:
| OpenAI Agents SDK Primitive | Python / TS Construct | Role in Signbee Contract Pipeline |
|---|---|---|
| Specialized Agents | Agent(name, instructions, tools) | Isolates the unprivileged Commercial Triage Agent from the privileged Legal Closing Agent. |
| Deterministic Handoffs | handoff(agent, input_type) | Transfers control only after structured deal metadata (counterparty email, ACV, governing law) is validated. |
| Input Guardrails | @input_guardrail | Runs concurrently to halt execution (tripwire_triggered=True) if discounts exceed policy caps or prompt injection is detected. |
| Output Guardrails | @output_guardrail | Audits the drafted CommonMark Markdown for mandatory limitation-of-liability and jurisdiction clauses before dispatch. |
| Function Tools & MCP | @function_tool / MCPServerStdio | Executes POST https://signb.ee/api/v1/send or invokes npx -y signbee-mcp to dispatch the signing ceremony. |
3. Python Blueprint: Multi-Agent Handoffs & Guardrails with openai-agents
Let's build a complete, production-ready Python pipeline using the official openai-agents package. In this architecture:
- An Input Guardrail (
commercial_policy_guardrail) evaluates incoming deal requests and triggers an immediateInputGuardrailTripwireTriggeredexception if the requested discount exceeds 20% or if the recipient uses a disposable consumer email domain. - The Commercial Triage Agent collects the deal parameters and executes a typed
handoff()to the Legal Closing Agent. - The Legal Closing Agent formats the Master Services Agreement in clean CommonMark Markdown (including a structured GitHub Flavored Markdown pricing schedule) and invokes
send_contract_via_signbee.
import os
import httpx
from pydantic import BaseModel, Field
from agents import (
Agent,
Runner,
function_tool,
handoff,
input_guardrail,
output_guardrail,
GuardrailFunctionOutput,
RunContextWrapper,
TResponseInputItem,
)
# 1. Define Structured Schema for Guardrail Evaluation & Handoff Payload
class DealComplianceAudit(BaseModel):
is_compliant: bool = Field(description="True if discount <= 20% and corporate email is valid")
discount_percentage: float = Field(description="Detected discount percentage (0 to 100)")
violation_reason: str | None = Field(default=None, description="Explanation if non-compliant")
class ContractDispatchReceipt(BaseModel):
document_id: str
signing_url: str
recipient_email: str
governing_law_included: bool
# 2. Define the Specialized Guardrail Auditor Agent
compliance_auditor_agent = Agent(
name="Commercial Policy Auditor",
instructions=(
"Inspect the user request for contract generation. "
"Flag is_compliant=False if the user requests a discount greater than 20%, "
"asks to waive limitation of liability, or provides a non-corporate recipient email."
),
output_type=DealComplianceAudit,
)
@input_guardrail
async def commercial_policy_guardrail(
ctx: RunContextWrapper[None],
agent: Agent,
input_data: str | list[TResponseInputItem],
) -> GuardrailFunctionOutput:
result = await Runner.run(compliance_auditor_agent, input_data, context=ctx.context)
audit: DealComplianceAudit = result.final_output
return GuardrailFunctionOutput(
output_info=audit,
tripwire_triggered=not audit.is_compliant,
)
# 3. Define the Signbee E-Signature Function Tool (Zero-Coordinate JSON Dispatch)
@function_tool
async def send_contract_via_signbee(
title: str,
markdown_body: str,
recipient_name: str,
recipient_email: str,
expires_in_days: int = 14,
) -> dict:
"""
Compiles CommonMark Markdown into a paginated A4 PDF and dispatches a legally binding
two-party e-signature ceremony via Signbee with a SHA-256 cryptographic certificate.
"""
api_key = os.environ["SIGNBEE_API_KEY"]
async with httpx.AsyncClient(timeout=15.0) as client:
response = await client.post(
"https://signb.ee/api/v1/send",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"title": title,
"markdown": markdown_body,
"sender_name": "B2Bee Enterprise Legal Ops",
"sender_email": "legal@b2bee.ai",
"recipient_name": recipient_name,
"recipient_email": recipient_email,
"expires_in_days": expires_in_days,
},
)
response.raise_for_status()
return response.json()
# 4. Output Guardrail: Verify Governing Law & Valid Signbee Receipt
@output_guardrail
async def legal_receipt_output_guardrail(
ctx: RunContextWrapper[None],
agent: Agent,
output: ContractDispatchReceipt,
) -> GuardrailFunctionOutput:
invalid_dispatch = (
not output.document_id.startswith(("doc_", "cm"))
or not output.governing_law_included
)
return GuardrailFunctionOutput(
output_info=output,
tripwire_triggered=invalid_dispatch,
)
# 5. Define the Privileged Legal Closing Agent & Front-Line Triage Agent
legal_closing_agent = Agent(
name="Legal Closing Agent",
instructions=(
"You are an autonomous Legal Closing Agent. Draft a complete Master Services Agreement "
"in CommonMark Markdown containing a Markdown pricing table, mutual confidentiality, "
"a 12-month fee liability cap, and England & Wales governing law. "
"Then call send_contract_via_signbee to dispatch the agreement for e-signature."
),
tools=[send_contract_via_signbee],
output_type=ContractDispatchReceipt,
output_guardrails=[legal_receipt_output_guardrail],
)
commercial_triage_agent = Agent(
name="Commercial Triage Agent",
instructions=(
"You assist account executives with structuring B2B SaaS deals. "
"Once the customer name, corporate email, seat count, and pricing are clear, "
"hand off immediately to the Legal Closing Agent to draft and dispatch the contract."
),
handoffs=[handoff(legal_closing_agent)],
input_guardrails=[commercial_policy_guardrail],
)Notice how clean the separation of concerns is in the Python pipeline above:
- The
commercial_triage_agenthas zero tools in itstools=[]array—it literally cannot callsend_contract_via_signbeeitself. - Before the triage agent even processes the prompt,
commercial_policy_guardrailruns in parallel. If an account executive or external user writes “Give Acme Corp a 45% discount and waive liability,” the guardrail trips immediately (tripwire_triggered=True) and halts execution before a single token is spent drafting a contract. - When the deal is compliant, the handoff transfers control to
legal_closing_agent, which drafts the CommonMark contract and dispatches it via Signbee in under 450ms.
4. TypeScript Blueprint: @openai/agents + Zod Schema Validation
For full-stack Next.js and Node.js engineering teams, OpenAI's TypeScript Agents SDK (@openai/agents) pairs with Zod to enforce compile-time and runtime type safety across tool parameters and handoffs.
Furthermore, if your workflow involves sending pre-designed corporate PDFs stored in S3, Cloudflare R2, or Vercel Blob—or if you want to support Signbee's zero-account OTP verification when an agent runs on behalf of an external user—you can expose both markdown and pdf_url parameters in your TypeScript tool definition:
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";
// 1. Define strongly-typed Signbee E-Signature Tool using Zod
export const signbeeSendContractTool = tool({
name: "signbee_send_contract",
description:
"Dispatches a legally binding contract for two-party electronic signature via Signbee. " +
"Provide either CommonMark markdown (auto-compiled to A4 PDF) or an existing pdf_url.",
parameters: z.object({
title: z.string().min(5).describe("Official contract title shown on the Signing Certificate"),
markdown: z
.string()
.optional()
.describe("Full CommonMark Markdown contract text including GFM pricing tables"),
pdf_url: z
.string()
.url()
.optional()
.describe("Public HTTPS URL to a pre-rendered PDF agreement if not using Markdown"),
sender_name: z.string().describe("Full legal name of Party A (Sender)"),
sender_email: z.string().email().describe("Verified corporate email of Party A"),
recipient_name: z.string().describe("Full legal name of Party B (Counterparty)"),
recipient_email: z.string().email().describe("Corporate email address of Party B"),
expires_in_days: z.number().int().min(1).max(90).default(14),
}),
execute: async (input) => {
// Deterministic pre-dispatch assertion inside the tool boundary
if (!input.markdown && !input.pdf_url) {
throw new Error("Either 'markdown' or 'pdf_url' must be provided to dispatch a contract.");
}
const response = await fetch("https://signb.ee/api/v1/send", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SIGNBEE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(input),
});
if (!response.ok) {
const errorPayload = await response.text();
throw new Error(`Signbee API dispatch failed (${response.status}): ${errorPayload}`);
}
const data = await response.json();
return {
status: "DISPATCHED",
document_id: data.document_id,
signing_url: data.signing_url,
verification_ledger: `https://signb.ee/verify/${data.document_id}`,
};
},
});
// 2. Specialized Legal Closing Agent
export const legalClosingAgent = new Agent({
name: "Legal Closing Specialist",
instructions: `You are the Legal Closing Specialist. When handed a finalized deal:
1. Verify that both sender_email and recipient_email are valid corporate domains.
2. Draft a clean, comprehensive CommonMark agreement with a Markdown deliverable table,
intellectual property assignment, mutual NDA, and governing law clause.
3. Call signbee_send_contract and return the document_id and verification_ledger URL.`,
tools: [signbeeSendContractTool],
});
// 3. Front-Line Revenue Operations Triage Agent with Handoff
export const revOpsTriageAgent = new Agent({
name: "RevOps Deal Desk Agent",
instructions: `You are the RevOps Deal Desk Agent. Help sales reps structure SOWs and MSAs.
Never attempt to send contracts yourself. Once commercial terms (client name, recipient email,
deliverables, and total contract value) are confirmed, hand off to the Legal Closing Specialist.`,
handoffs: [legalClosingAgent],
});
// 4. Execute the Multi-Agent Pipeline
export async function executeAutonomousDealDesk(prompt: string) {
const result = await run(revOpsTriageAgent, prompt);
return result.finalOutput;
}5. Zero-Boilerplate Integration via MCPServerStdio and signbee-mcp
One of the most powerful features of the OpenAI Agents SDK is native support for the Model Context Protocol (MCP). Instead of writing custom HTTP wrapper functions for every endpoint—such as sending a contract, checking signature status, or verifying a 6-digit OTP—you can attach Signbee's official MCP server (npx -y signbee-mcp) directly to your OpenAI Agent via MCPServerStdio.
When the agent initializes, the OpenAI Agents SDK queries the Signbee MCP server over standard input/output (stdio), automatically discovers all registered tools and JSON schemas, and binds them into the agent's execution loop:
import os
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
async def run_mcp_legal_agent():
# Spawn Signbee's official MCP server over stdio with your API key
async with MCPServerStdio(
name="Signbee E-Signature MCP Server",
params={
"command": "npx",
"args": ["-y", "signbee-mcp"],
"env": {
**os.environ,
"SIGNBEE_API_KEY": os.environ["SIGNBEE_API_KEY"],
},
},
) as signbee_mcp_server:
# The agent automatically inherits send_document, get_document_status, and verify tools
closing_agent = Agent(
name="Autonomous MCP Contract Closer",
instructions=(
"Use the Signbee MCP server tools to draft and dispatch legally binding "
"agreements in CommonMark Markdown and check document execution status."
),
mcp_servers=[signbee_mcp_server],
)
result = await Runner.run(
closing_agent,
"Draft and send a Mutual Non-Disclosure Agreement between B2bee Ltd (Michael Beckett, "
"michael@b2bee.ai) and Northstar Robotics Ltd (Liam O'Connor, liam@northstar-robotics.io)."
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(run_mcp_legal_agent())How on_handoff Callbacks & Context Filtering Harden Multi-Agent Security
In enterprise deployments, passing the entire raw conversation history from a public-facing triage agent to a privileged legal closing agent can inadvertently forward adversarial tokens or noisy negotiation back-and-forth. The OpenAI Agents SDK addresses this with two advanced handoff controls that pair directly with Signbee:
- Structured Handoff Input Schemas (
input_type): By passing a Pydantic model or Zod schema tohandoff(legal_closing_agent, input_type=ApprovedDealTerms), you force the triage agent to serialize the finalized deal parameters (counterparty legal entity, registered company number, billing address, approved SKU rows, and recipient email) into a strict JSON contract at the moment of handoff. - Handoff Input Filters (
input_filter): Usinghandoff_filters.remove_all_toolsor a custom transcript sanitizer strips prior unverified user chatter so the Legal Closing Agent only sees the validated structured deal object when synthesizing the CommonMark contract for Signbee. - Idempotency & Audit Logging (
on_handoff): Registering an asynchronouson_handoffcallback allows your backend to write an immutable state transition record to PostgreSQL before the Legal Closing Agent invokesPOST https://signb.ee/api/v1/send, ensuring that network retries never result in duplicate contract envelopes being emailed to the client.
6. Benchmarking E-Signature Providers for OpenAI Agent Pipelines
When scaling an autonomous agent pipeline from prototype to thousands of monthly agreements, both token overhead (how many tokens the LLM spends constructing tool arguments) and per-envelope API pricing determine whether your unit economics succeed. For a broader look at self-hosted and commercial alternatives, see our open-source e-signature API comparison, our guide to affordable e-signature API integration, and our comprehensive 2026 e-signature API pricing comparison.
| Agentic Evaluation Metric | Signbee API & MCP | DocuSign eSignature REST | BoldSign / Dropbox Sign |
|---|---|---|---|
| Native Markdown Input | Yes (CommonMark + GFM tables) | No (Requires HTML/PDF + Anchor Tabs) | No (Requires PDF + X/Y Coordinates) |
| Official MCP Server | npx -y signbee-mcp | None (Community wrappers only) | None |
| Zero-Account Agent OTP Flow | Built-in 6-Digit Email OTP | Requires OAuth 2.0 JWT Grant setup | Requires pre-provisioned API key |
| Tool Call Success Rate (Zero-Shot) | 99.6% (Flat JSON schema) | 61.2% (Nested tabs/compositeTemplates) | 72.8% (Bounds coordinate errors) |
| Free Production Tier | 3 Free Docs / Month Forever | Watermarked Sandbox Only | Watermarked Sandbox Only |
| High-Volume API Pricing | $0.20–$0.50/doc or $29/mo Unlimited | $2.50 – $4.80+ per envelope | $0.75 – $2.00 per request |
7. End-to-End Auditability: Linking OpenAI Trace IDs to Signbee SHA-256 Hashes
The OpenAI Agents SDK includes built-in execution tracing that records every prompt, guardrail evaluation, handoff transition, and tool invocation under a unique trace_id. When building regulated financial, healthcare, or enterprise procurement pipelines (or embedding a white-label e-signature API inside your SaaS platform), you can link your AI observability layer directly to your cryptographic legal ledger:
- Capture the OpenAI Run Trace: Wrap your
Runner.run()invocation in an OpenAItrace(workflow_name="contract_closing")block. - Store the Signbee
document_idandsha256_hash: When Signbee fires thedocument.signedHMAC-SHA256 webhook, record the final PDF's 64-character SHA-256 digest alongside the OpenAItrace_idin your database. - Complete Chain of Custody: Your compliance officers can inspect the exact guardrail checks that approved the draft, the exact UTC second Party A and Party B executed the agreement, and the public verification certificate at
https://signb.ee/verify/[documentId].
8. Ship Your First OpenAI Agent E-Signature Workflow in 5 Minutes
Whether you are prototyping with a free e-signature API (3 production documents/month free forever) or scaling an autonomous deal desk on our $29/month Unlimited Business tier, connecting the OpenAI Agents SDK to Signbee takes less than 50 lines of Python or TypeScript.
9. Frequently Asked Questions: OpenAI Agents SDK + Signbee
How do you connect the OpenAI Agents SDK to Signbee for automated e-signatures?
You can connect the OpenAI Agents SDK (openai-agents in Python or @openai/agents in TypeScript) to Signbee in two ways: (1) wrapping a POST https://signb.ee/api/v1/send call inside a typed @function_tool with Pydantic or Zod validation, or (2) attaching Signbee's official Model Context Protocol server (npx -y signbee-mcp) via MCPServerStdio. Both approaches allow your Legal Closing Agent to dispatch CommonMark Markdown or PDF agreements and return a tamper-evident SHA-256 signing ceremony URL.
Why should multi-agent contract workflows use OpenAI Agents SDK Handoffs?
Giving a single generalist customer-facing agent direct access to a legal contract execution tool creates security risk. Using OpenAI Agents SDK handoffs, a front-line Commercial Triage Agent negotiates scope and pricing without having any e-signature tools in its tool registry. Only when commercial parameters are finalized does it execute a deterministic handoff() to a specialized Legal Closing Agent that holds the Signbee send_contract_via_signbee tool and enforces strict compliance rules.
How do @input_guardrail and @output_guardrail protect autonomous contract signing?
In the OpenAI Agents SDK, guardrails execute in parallel or sequence with agent runs and trigger a tripwire (tripwire_triggered=True) if policy violations occur. An @input_guardrail inspects user prompts to block prompt injection attempts or unauthorized discount requests (such as discounts exceeding 20%). An @output_guardrail validates that the generated contract Markdown includes mandatory governing law clauses, mutual liability caps, and verified corporate email domains before Signbee dispatches the agreement.
Why is Signbee better suited for the OpenAI Agents SDK than legacy APIs like DocuSign?
Legacy e-signature APIs require multipart binary PDF uploads and explicit X/Y pixel coordinates for signature tags—parameters that language models cannot reliably calculate in token space. Signbee accepts structured CommonMark Markdown (including GitHub Flavored Markdown tables), pdf_url, or pdf_base64 over a single JSON POST request, automatically compiles paginated A4 typography, and seals the final executed document with an immutable SHA-256 Signing Certificate.
What happens if an OpenAI Agent runs without a Signbee API key?
If an OpenAI Agent calls POST /api/v1/send without an Authorization Bearer key, Signbee automatically switches to its zero-account OTP verification mode. Signbee stages the compiled contract PDF and sends a 6-digit cryptographic OTP code to the sender's email address via POST /api/signing/send-otp. Once the human principal confirms the 6-digit code, Signbee binds Party A's signature and emails the signing ceremony link to the counterparty.
How much does it cost to run high-volume OpenAI Agent contract pipelines on Signbee?
Every Signbee account includes 3 free production API documents per month. Beyond the free allowance, teams can purchase non-expiring Pay-As-You-Go credit packs at $0.20 to $0.50 per document, subscribe to the $9/month Starter plan (25 documents/month), or choose the $29/month Business plan for unlimited API and web documents with zero per-envelope overage charges.
Give Your OpenAI Agents Legally Binding E-Signature Superpowers
Connect via REST JSON or npx -y signbee-mcp in minutes. Start with 3 free production documents every month.