mech.app

The mech.app newsletter

Agentic AI, minus the noise.

Get practical field notes on AI agents, automation, developer tools and security delivered to your inbox.

No spam. Unsubscribe anytime.

Dev Tools

Twenty's Open CRM Architecture: How Agent-First Design Turns Customer Data into Executable Workflows

Twenty exposes CRM entities as GraphQL primitives, letting agents query contacts, mutate deals, and orchestrate pipeline stages without custom integrati...

Source: github.com
Twenty's Open CRM Architecture: How Agent-First Design Turns Customer Data into Executable Workflows

Twenty bills itself as “designed for AI,” but what does that mean when you trace the plumbing? Most CRMs treat automation as an afterthought: webhook endpoints bolted onto a UI-first data model, with agents forced to scrape HTML or reverse-engineer undocumented APIs. Twenty flips the contract. Its GraphQL schema exposes contacts, deals, tasks, and pipeline stages as introspectable primitives. Agents read and mutate CRM state the same way humans do, through a typed API surface that treats customer lifecycle events as first-class resources.

This matters for financial and sales automation. Lead scoring, pipeline progression, outreach sequencing, and revenue forecasting all depend on reading relationship state and writing back decisions. Twenty’s architecture reveals how a modern CRM becomes agent infrastructure: PostgreSQL for queryable state, NestJS for mutation boundaries, and a workflow engine that surfaces field changes and stage transitions as event streams.

GraphQL as the Agent Contract

Twenty’s primary interface is a GraphQL API. No REST fallback, no legacy SOAP layer. The schema defines every entity (Person, Company, Opportunity, Task) and every relationship (Person.company, Opportunity.pointOfContact) as typed fields. Agents introspect the schema at runtime, discover available mutations, and construct queries without hardcoded field names.

Key primitives for agents:

  • Queries: findManyPeople, findOneOpportunity, searchCompanies return paginated, filterable result sets. Agents can pass GraphQL variables for dynamic filtering (e.g., where: { stage: { eq: "QUALIFIED" } }).
  • Mutations: createOnePerson, updateOneOpportunity, deleteOneTask accept input objects that match the schema. State transitions (moving a deal from “Qualified” to “Proposal”) are just field updates on the Opportunity.stage enum.
  • Subscriptions: Real-time updates when records change. An agent watching for new leads subscribes to personCreated and receives push notifications without polling.

The schema is code-generated from TypeScript decorators in the NestJS backend. When you define a new custom field in Twenty’s UI, the GraphQL schema regenerates automatically. Agents see the new field in the next introspection query.

PostgreSQL Data Model and State Management

Twenty stores all CRM data in PostgreSQL. Each workspace gets its own schema (logical isolation within a single database). The core tables mirror the GraphQL types:

  • person: contacts with email, phone, LinkedIn URL
  • company: organizations with domain, employee count, industry
  • opportunity: deals with amount, stage, close date
  • activity: tasks, notes, emails linked to people or companies
  • workflow_run: execution history for automated sequences

State transitions are row updates. When an agent moves a deal to “Closed Won,” it issues an updateOneOpportunity mutation that writes a new stage value and closedAt timestamp. PostgreSQL triggers can fire on these updates to log audit events or cascade changes (e.g., updating a company’s total deal value when an opportunity closes).

Multi-tenancy boundaries: Each workspace is a separate schema. Agents operating across workspaces must authenticate per-workspace and cannot query across schema boundaries without explicit federation. This prevents accidental data leakage but complicates cross-workspace orchestration (e.g., a holding company agent managing deals across subsidiary workspaces).

Workflow Engine and Event-Driven Triggers

Twenty includes a workflow engine that turns CRM events into agent triggers. Workflows are defined as directed acyclic graphs (DAGs) where nodes represent actions (send email, update field, call webhook) and edges represent conditional logic.

Event sources that trigger workflows:

  • Field changes: When Opportunity.stage moves from “Proposal” to “Negotiation,” fire a workflow that notifies the sales manager and schedules a follow-up task.
  • Record creation: When a new Person is created with leadSource: "Website", enrich the contact with Clearbit data and assign to the inbound sales queue.
  • Time-based: Daily cron job that finds all opportunities with closeDate in the past and stage != "Closed Lost" and sends a reminder.

Webhook delivery for external orchestrators: Twenty can POST workflow events to external URLs. An agent orchestrator (LangGraph, Temporal, n8n) listens for these webhooks and decides whether to intervene. For example:

  1. Deal moves to “Negotiation.”
  2. Twenty fires a webhook to https://orchestrator.example.com/deal-negotiation.
  3. Orchestrator queries the deal details via GraphQL, runs a pricing model, and posts a recommended discount back to Twenty as a note on the opportunity.

The workflow engine tracks execution state in workflow_run and workflow_step tables. If a webhook fails, Twenty retries with exponential backoff. Agents can query these tables to audit past runs and debug stuck workflows.

Agent Tool Boundaries and Mutation Surface

From an agent’s perspective, Twenty exposes these tool categories:

Tool CategoryExample OperationsState Changes
Contact ManagementcreatePerson, updatePerson, searchPeopleInserts/updates in person table
Deal ProgressioncreateOpportunity, updateOpportunity.stageUpdates opportunity.stage, logs audit event
Task OrchestrationcreateActivity, updateActivity.statusInserts/updates in activity, triggers reminders
EnrichmentenrichCompany (custom function)Calls external API, writes to company.metadata JSONB field
ReportingaggregateOpportunities (custom resolver)Read-only query across opportunity with SUM/AVG

Custom functions as agent tools: Twenty lets you define custom GraphQL resolvers in TypeScript. An agent can call enrichCompany(domain: "example.com") which internally hits Clearbit, Apollo, or another data provider and writes enriched fields back to the company record. These custom resolvers are versioned alongside the schema, so agents always see the latest tool signature.

Permission boundaries: Twenty uses role-based access control (RBAC) at the GraphQL resolver level. An agent authenticated with a service account token inherits the permissions of that account’s role. If the role lacks update:opportunity permission, the agent’s mutation fails with a 403. This prevents rogue agents from escalating privileges or mutating sensitive records.

Audit Logging and Agent Attribution

Every mutation in Twenty writes to an audit log table (audit_event). The log captures:

  • Actor: user ID or service account ID (agent token)
  • Action: CREATE, UPDATE, DELETE
  • Entity: table name and record ID
  • Changes: JSON diff of old vs. new field values
  • Timestamp: when the mutation occurred

Distinguishing agent actions from human actions: Service accounts are flagged with isServiceAccount: true. Queries against audit_event can filter by actor type to separate agent-initiated mutations from human edits. This is critical for compliance (e.g., proving that a discount was applied by an AI agent following a pricing policy, not a rogue salesperson).

Replay and rollback: Because the audit log stores JSON diffs, you can reconstruct the state of any record at any point in time. If an agent makes a bad decision (e.g., marks all deals as “Closed Lost”), you can query the audit log, identify the offending mutations, and issue compensating transactions to revert the changes.

Deployment Shape and Observability

Twenty ships as a Docker Compose stack for self-hosting or runs on their managed cloud. The core services:

  • twenty-server: NestJS backend, GraphQL API, workflow engine
  • twenty-frontend: React SPA, admin UI
  • postgres: PostgreSQL 15 with pgvector for semantic search
  • redis: Job queue for async workflows and webhook retries
  • worker: Background job processor (emails, enrichment, scheduled workflows)

Observability hooks for agents:

  • Metrics: Prometheus endpoint at /metrics exposes GraphQL query latency, mutation error rates, and workflow execution counts.
  • Traces: OpenTelemetry instrumentation tags each GraphQL operation with operation_name, user_id, and workspace_id. Agents can correlate their tool calls with backend traces in Jaeger or Honeycomb.
  • Logs: Structured JSON logs include correlation_id for tracing a single agent request across multiple services (e.g., GraphQL mutation triggers workflow, workflow calls webhook, webhook updates record).

Failure modes agents must handle:

  • Rate limits: Twenty enforces per-workspace rate limits (e.g., 1000 requests/minute). Agents must implement exponential backoff and respect Retry-After headers.
  • Schema drift: If a custom field is deleted, agents querying that field receive a GraphQL error. Agents should catch schema errors and re-introspect before retrying.
  • Webhook delivery failures: If an agent’s webhook endpoint is down, Twenty retries for 24 hours then marks the workflow as failed. Agents must monitor workflow_run.status and manually replay failed runs.

Code Example: Agent Tool for Deal Progression

Here’s how an agent would wrap Twenty’s GraphQL API as a tool for moving deals through the pipeline:

import { GraphQLClient } from 'graphql-request';

class TwentyCRMTool {
  private client: GraphQLClient;

  constructor(apiUrl: string, apiKey: string) {
    this.client = new GraphQLClient(apiUrl, {
      headers: { Authorization: `Bearer ${apiKey}` }
    });
  }

  async moveDealToStage(opportunityId: string, newStage: string): Promise<void> {
    const mutation = `
      mutation UpdateOpportunity($id: ID!, $stage: String!) {
        updateOneOpportunity(
          where: { id: $id }
          data: { stage: $stage }
        ) {
          id
          stage
          updatedAt
        }
      }
    `;

    const variables = { id: opportunityId, stage: newStage };
    const result = await this.client.request(mutation, variables);
    
    console.log(`Deal ${result.updateOneOpportunity.id} moved to ${result.updateOneOpportunity.stage}`);
  }

  async getDealsInStage(stage: string): Promise<any[]> {
    const query = `
      query FindOpportunities($stage: String!) {
        findManyOpportunities(
          where: { stage: { eq: $stage } }
          orderBy: { closeDate: ASC }
        ) {
          id
          name
          amount
          closeDate
          pointOfContact { name email }
        }
      }
    `;

    const variables = { stage };
    const result = await this.client.request(query, variables);
    return result.findManyOpportunities;
  }
}

// Agent usage
const crm = new TwentyCRMTool('https://api.twenty.com/graphql', process.env.TWENTY_API_KEY);

// Get all deals in "Negotiation" stage
const deals = await crm.getDealsInStage('NEGOTIATION');

// Move the first deal to "Closed Won"
if (deals.length > 0) {
  await crm.moveDealToStage(deals[0].id, 'CLOSED_WON');
}

The agent treats moveDealToStage and getDealsInStage as tools. The GraphQL client handles retries, error parsing, and token refresh. The agent’s orchestrator (LangGraph, CrewAI, etc.) calls these tools based on its decision logic.

Security Boundaries and Token Scoping

Twenty uses JWT tokens for authentication. Each token is scoped to a workspace and a role. Agents receive service account tokens with limited permissions:

  • Read-only tokens: Can query all entities but cannot mutate. Useful for reporting agents that aggregate pipeline metrics.
  • Write tokens: Can create and update records but cannot delete. Useful for enrichment agents that add data without removing it.
  • Admin tokens: Full CRUD access. Reserved for orchestrators that manage workspace configuration.

Token rotation: Service account tokens expire after 90 days. Agents must implement token refresh logic or store tokens in a secrets manager (AWS Secrets Manager, HashiCorp Vault) that rotates them automatically.

IP allowlisting: Self-hosted Twenty instances can restrict API access to specific IP ranges. Agents running in a VPC must route through a NAT gateway with a static IP.

Technical Verdict

Use Twenty when:

  • You need a CRM that agents can introspect and mutate without custom integration code.
  • Your sales or financial workflows require reading pipeline state and writing back decisions (lead scoring, discount approval, forecast updates).
  • You want audit logs that distinguish agent actions from human actions for compliance.
  • You’re comfortable running a TypeScript/PostgreSQL stack and need to extend the CRM with custom resolvers.

Avoid Twenty when:

  • You need a CRM with pre-built integrations to legacy systems (Salesforce has 3000+ connectors, Twenty has dozens).
  • Your agents must operate across multiple CRMs and you need a unified abstraction layer (consider a middleware like Merge or Vessel instead).
  • You require real-time collaboration features (live cursors, conflict resolution) for human-agent co-editing.
  • Your compliance regime prohibits self-hosting or requires FedRAMP/HIPAA certification (Twenty’s managed cloud is not yet certified).

Twenty’s architecture is a blueprint for agent-first SaaS: expose your data model as a typed API, surface state changes as events, and let agents treat your product as infrastructure. The GraphQL contract and PostgreSQL backing store make it straightforward to build agents that read, write, and orchestrate customer lifecycle workflows without wrestling with REST pagination or webhook flakiness.