Tessorium // Docs
GET_STARTED
root@tessorium:~/docs/integrations$_

Integration Guides

Production-ready integration patterns for enterprise deployments.

OVERVIEW

Tessorium TTP integrates with popular frameworks and deployment patterns. Choose the integration that matches your stack for production-ready trust verification.

WEB_FRAMEWORKS

  • Express.js middleware
  • Next.js middleware & server actions
  • Fastify plugin
  • Hono middleware

AI_FRAMEWORKS

  • LangChain callback handlers
  • CrewAI agent decorators
  • AutoGPT plugins
  • MCP Server integration

INFRASTRUCTURE

  • Kubernetes sidecar
  • Docker Compose
  • AWS Lambda layers
  • Cloudflare Workers

OBSERVABILITY

  • OpenTelemetry spans
  • Datadog integration
  • Splunk logging
  • PagerDuty alerts

EXPRESS.JS_INTEGRATION

Add trust verification to Express.js applications with middleware.

INSTALLATION

bash
npm install @tessorium/sdk @tessorium/express

BASIC_SETUP

server.ts
import express from 'express';
import { tessoriumMiddleware } from '@tessorium/express';

const app = express();

// Global middleware - verify all requests
app.use(tessoriumMiddleware({
  apiKey: process.env.TESSORIUM_API_KEY!,
  minTrustScore: 70,

  // How to extract agent DID from request
  extractAgentDid: (req) => {
    // From header
    return req.headers['x-agent-did'] as string ||
      // Or from JWT
      req.user?.agentDid ||
      // Or from query param
      req.query.agentDid as string;
  },

  // Skip verification for certain paths
  skipPaths: ['/health', '/metrics', '/public'],

  // Custom error handler
  onVerificationFailed: (req, res, result) => {
    res.status(403).json({
      error: 'Trust verification failed',
      stage: result.stage,
      reason: result.reason
    });
  }
}));

// Your routes
app.post('/api/agent-action', (req, res) => {
  // Trust info available on request
  const { trust } = req.tessorium;
  console.log(`Agent ${trust.did} with score ${trust.score}`);

  res.json({ success: true });
});

app.listen(3000);

ROUTE_SPECIFIC_POLICIES

routes.ts
import { Router } from 'express';
import { tessoriumMiddleware, requireTrust } from '@tessorium/express';

const router = Router();

// Different trust levels for different routes
router.post('/api/low-risk',
  requireTrust({ minScore: 50, stage: 'new' }),
  handleLowRisk
);

router.post('/api/medium-risk',
  requireTrust({ minScore: 70, stage: 'building' }),
  handleMediumRisk
);

router.post('/api/high-risk',
  requireTrust({
    minScore: 85,
    stage: 'established',
    requireIdentity: true,
    scopes: ['financial', 'data_write']
  }),
  handleHighRisk
);

// Combine with human oversight for critical actions
router.post('/api/critical-action',
  requireTrust({ minScore: 90 }),
  requireHumanApproval({
    action: 'critical_operation',
    timeout: 30 * 60 * 1000  // 30 minutes
  }),
  handleCriticalAction
);

export default router;

TYPE_AUGMENTATION

types/express.d.ts
import { UnifiedTrustResult } from '@tessorium/sdk';

declare global {
  namespace Express {
    interface Request {
      tessorium: {
        trust: UnifiedTrustResult;
        agentDid: string;
        verifiedAt: Date;
      };
    }
  }
}

NEXT.JS_INTEGRATION

Protect Next.js API routes and server actions with trust verification.

MIDDLEWARE

middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createTessoriumEdge } from '@tessorium/sdk/edge';

const tessorium = createTessoriumEdge({
  apiKey: process.env.TESSORIUM_API_KEY!
});

export async function middleware(request: NextRequest) {
  // Only protect /api/agent/* routes
  if (!request.nextUrl.pathname.startsWith('/api/agent/')) {
    return NextResponse.next();
  }

  const agentDid = request.headers.get('x-agent-did');

  if (!agentDid) {
    return NextResponse.json(
      { error: 'Missing agent DID' },
      { status: 401 }
    );
  }

  try {
    const trust = await tessorium.verify(agentDid);

    if (!trust.trusted) {
      return NextResponse.json(
        {
          error: 'Trust verification failed',
          stage: trust.stage,
          reason: trust.reason
        },
        { status: 403 }
      );
    }

    // Pass trust info to route handlers
    const response = NextResponse.next();
    response.headers.set('x-tessorium-did', trust.did);
    response.headers.set('x-tessorium-score', String(trust.score));
    response.headers.set('x-tessorium-stage', trust.stage);

    return response;
  } catch (error) {
    console.error('Trust verification error:', error);
    return NextResponse.json(
      { error: 'Trust verification unavailable' },
      { status: 503 }
    );
  }
}

export const config = {
  matcher: '/api/agent/:path*'
};

API_ROUTE_HANDLER

app/api/agent/action/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { createApiClient } from '@tessorium/sdk';

const tessorium = createApiClient(process.env.TESSORIUM_API_KEY!);

export async function POST(request: NextRequest) {
  // Trust already verified by middleware
  const agentDid = request.headers.get('x-tessorium-did')!;
  const trustScore = parseInt(request.headers.get('x-tessorium-score')!);
  const trustStage = request.headers.get('x-tessorium-stage')!;

  const body = await request.json();

  // Additional scope-based checks if needed
  if (body.action === 'financial_operation' && trustScore < 85) {
    return NextResponse.json(
      { error: 'Insufficient trust for financial operations' },
      { status: 403 }
    );
  }

  // Process the action
  const result = await processAgentAction(body);

  // Rate the interaction
  await tessorium.rate(agentDid, {
    outcome: result.success ? 'success' : 'failure',
    dimensions: {
      reliability: result.success ? 5 : 2,
      quality: 4,
      speed: 5,
      safety: 5
    },
    wouldWorkAgain: result.success
  });

  return NextResponse.json(result);
}

SERVER_ACTION

app/actions/agent-actions.ts
'use server'

import { createApiClient } from '@tessorium/sdk';
import { headers } from 'next/headers';

const tessorium = createApiClient(process.env.TESSORIUM_API_KEY!);

export async function executeAgentTask(taskData: TaskInput) {
  const headersList = headers();
  const agentDid = headersList.get('x-agent-did');

  if (!agentDid) {
    throw new Error('No agent DID provided');
  }

  // Verify trust
  const trust = await tessorium.verify(agentDid);

  if (!trust.trusted) {
    throw new Error(`Agent not trusted: ${trust.reason}`);
  }

  // Check specific capability requirements
  if (taskData.requiresDataAccess) {
    const scopeTrust = await tessorium.verify(agentDid, {
      scopes: ['data_read']
    });

    if (scopeTrust.scopes?.data_read !== 'high') {
      throw new Error('Insufficient data access trust');
    }
  }

  // Execute the task
  const result = await performTask(taskData);

  return result;
}

KUBERNETES_SIDECAR

Deploy the Gateway Proxy as a sidecar container for zero-code trust enforcement.

POD_SPEC

k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ai-agent-deployment
  labels:
    app: ai-agent
spec:
  replicas: 3
  selector:
    matchLabels:
      app: ai-agent
  template:
    metadata:
      labels:
        app: ai-agent
      annotations:
        tessorium.io/inject: "true"
        tessorium.io/min-trust-score: "70"
    spec:
      containers:
      # Your AI agent container
      - name: ai-agent
        image: your-registry/ai-agent:latest
        ports:
          - containerPort: 8000
        env:
          # Route traffic through sidecar
          - name: OUTBOUND_PROXY
            value: "http://localhost:8080"

      # Tessorium Gateway Sidecar
      - name: tessorium-sidecar
        image: tessorium/gateway-proxy:latest
        ports:
          - containerPort: 8080
        env:
          - name: TESSORIUM_API_KEY
            valueFrom:
              secretKeyRef:
                name: tessorium-secrets
                key: api-key
          - name: MIN_TRUST_SCORE
            value: "70"
          - name: BLOCK_UNVERIFIED
            value: "true"
          - name: AUDIT_ENABLED
            value: "true"
          - name: METRICS_PORT
            value: "9090"
        resources:
          limits:
            cpu: "100m"
            memory: "128Mi"
          requests:
            cpu: "50m"
            memory: "64Mi"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

CONFIGMAP

k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: tessorium-config
data:
  policy.yaml: |
    policy:
      name: production-default
      version: "1.0"

    trust_requirements:
      default:
        min_score: 70
        require_identity: true

      routes:
        - path: "/api/public/*"
          min_score: 0

        - path: "/api/internal/*"
          min_score: 80
          require_stage: "building"

        - path: "/api/sensitive/*"
          min_score: 90
          require_stage: "established"
          require_human_approval: true

    audit:
      enabled: true
      log_level: "standard"
      retention_days: 90

SECRETS

k8s/secrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: tessorium-secrets
type: Opaque
data:
  # Base64 encoded API key
  api-key: dHNyX2xpdmVfeHh4eHh4eHh4eHh4
---
# For production, use External Secrets Operator
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: tessorium-secrets
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-backend
    kind: ClusterSecretStore
  target:
    name: tessorium-secrets
    creationPolicy: Owner
  data:
    - secretKey: api-key
      remoteRef:
        key: tessorium/production
        property: api-key

HELM_CHART

helm/values.yaml
tessorium:
  enabled: true
  image:
    repository: tessorium/gateway-proxy
    tag: "1.0.4"

  config:
    minTrustScore: 70
    blockUnverified: true
    auditEnabled: true

  resources:
    limits:
      cpu: 100m
      memory: 128Mi
    requests:
      cpu: 50m
      memory: 64Mi

  # Enable ServiceMonitor for Prometheus
  metrics:
    enabled: true
    port: 9090
    serviceMonitor:
      enabled: true
      interval: 30s

MCP_SERVER_INTEGRATION

Add trust verification to Model Context Protocol (MCP) servers for tool-calling AI agents.

MCP_SERVER_SETUP

mcp-server.ts
import { Server } from '@modelcontextprotocol/sdk/server';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio';
import { createApiClient } from '@tessorium/sdk';

const tessorium = createApiClient(process.env.TESSORIUM_API_KEY!);

const server = new Server(
  {
    name: 'trusted-tools-server',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {}
    }
  }
);

// Wrap tool handlers with trust verification
function withTrustVerification<T extends (...args: any[]) => Promise<any>>(
  handler: T,
  options: { minScore?: number; scopes?: string[] } = {}
) {
  return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
    const context = args[0];
    const agentDid = context?.meta?.agentDid;

    if (!agentDid) {
      throw new Error('No agent DID in request context');
    }

    const trust = await tessorium.verify(agentDid, {
      scopes: options.scopes
    });

    const minScore = options.minScore ?? 70;
    if (!trust.score || trust.score < minScore) {
      throw new Error(
        `Trust score ${trust.score} below required ${minScore}`
      );
    }

    return handler(...args);
  };
}

// Define tools with trust requirements
server.setRequestHandler('tools/list', async () => ({
  tools: [
    {
      name: 'read_file',
      description: 'Read a file from the filesystem',
      inputSchema: {
        type: 'object',
        properties: {
          path: { type: 'string' }
        },
        required: ['path']
      }
    },
    {
      name: 'execute_code',
      description: 'Execute code in a sandboxed environment',
      inputSchema: {
        type: 'object',
        properties: {
          language: { type: 'string' },
          code: { type: 'string' }
        },
        required: ['language', 'code']
      }
    }
  ]
}));

server.setRequestHandler('tools/call', async (request) => {
  const { name, arguments: args } = request.params;

  switch (name) {
    case 'read_file':
      return withTrustVerification(
        readFileHandler,
        { minScore: 60, scopes: ['data_read'] }
      )(request);

    case 'execute_code':
      return withTrustVerification(
        executeCodeHandler,
        { minScore: 85, scopes: ['code_execution'] }
      )(request);

    default:
      throw new Error(`Unknown tool: ${name}`);
  }
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch(console.error);

CLIENT_CONFIGURATION

mcp-config.json
{
  "mcpServers": {
    "trusted-tools": {
      "command": "node",
      "args": ["./mcp-server.js"],
      "env": {
        "TESSORIUM_API_KEY": "tsr_live_xxxx"
      },
      "metadata": {
        "agentDid": "did:tessorium:agent:my-agent:v1"
      }
    }
  }
}

LANGCHAIN_INTEGRATION

Add trust verification callbacks to LangChain agents and chains.

langchain-integration.ts
import { BaseCallbackHandler } from 'langchain/callbacks';
import { createApiClient } from '@tessorium/sdk';

const tessorium = createApiClient(process.env.TESSORIUM_API_KEY!);

class TessoriumCallbackHandler extends BaseCallbackHandler {
  name = 'TessoriumCallbackHandler';

  private agentDid: string;
  private minTrustScore: number;

  constructor(options: { agentDid: string; minTrustScore?: number }) {
    super();
    this.agentDid = options.agentDid;
    this.minTrustScore = options.minTrustScore ?? 70;
  }

  async handleToolStart(
    tool: { name: string },
    input: string
  ): Promise<void> {
    // Verify trust before tool execution
    const trust = await tessorium.verify(this.agentDid, {
      scopes: [this.getToolScope(tool.name)]
    });

    if (!trust.trusted || (trust.score && trust.score < this.minTrustScore)) {
      throw new Error(
        `Trust verification failed for tool ${tool.name}: ${trust.reason}`
      );
    }

    console.log(
      'Tool ' + tool.name + ' authorized for agent ' + this.agentDid +
      ' (score: ' + trust.score + ')'
    );
  }

  async handleToolEnd(output: string): Promise<void> {
    // Optional: Log tool completion for audit
  }

  async handleChainEnd(outputs: Record<string, any>): Promise<void> {
    // Rate the interaction
    await tessorium.rate(this.agentDid, {
      outcome: 'success',
      dimensions: {
        reliability: 5,
        quality: 4,
        speed: 5,
        safety: 5
      },
      wouldWorkAgain: true
    });
  }

  async handleChainError(error: Error): Promise<void> {
    // Rate failed interaction
    await tessorium.rate(this.agentDid, {
      outcome: 'failure',
      dimensions: {
        reliability: 2,
        quality: 2,
        speed: 3,
        safety: 5
      },
      wouldWorkAgain: false
    });
  }

  private getToolScope(toolName: string): string {
    const scopeMap: Record<string, string> = {
      'search': 'data_read',
      'calculator': 'general',
      'code_interpreter': 'code_execution',
      'file_writer': 'data_write'
    };
    return scopeMap[toolName] ?? 'general';
  }
}

// Usage with LangChain agent
import { initializeAgentExecutorWithOptions } from 'langchain/agents';
import { ChatOpenAI } from 'langchain/chat_models/openai';

const model = new ChatOpenAI({ temperature: 0 });

const executor = await initializeAgentExecutorWithOptions(
  tools,
  model,
  {
    agentType: 'chat-conversational-react-description',
    callbacks: [
      new TessoriumCallbackHandler({
        agentDid: 'did:tessorium:agent:langchain-agent:v1',
        minTrustScore: 75
      })
    ]
  }
);

CREWAI_INTEGRATION

Integrate trust verification into CrewAI multi-agent workflows.

crewai-integration.py
from crewai import Agent, Task, Crew
from functools import wraps
import httpx
import os

class TessoriumClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.tessorium.ai/v1"

    def verify(self, did: str, min_score: int = 70) -> dict:
        response = httpx.get(
            f"{self.base_url}/trust/{did}",
            headers={"Authorization": f"Bearer {self.api_key}"}
        )
        response.raise_for_status()
        data = response.json()["data"]["attestation"]

        if data["trust"]["score"] < min_score:
            raise ValueError(
                f"Trust score {data['trust']['score']} below minimum {min_score}"
            )

        return data["trust"]

    def rate(self, did: str, outcome: str, dimensions: dict):
        httpx.post(
            f"{self.base_url}/ratings",
            headers={"Authorization": f"Bearer {self.api_key}"},
            json={
                "subjectDid": did,
                "outcome": outcome,
                "dimensions": dimensions,
                "wouldWorkAgain": outcome == "success"
            }
        )

tessorium = TessoriumClient(os.environ["TESSORIUM_API_KEY"])

def require_trust(min_score: int = 70, scopes: list = None):
    """Decorator to require trust verification before agent execution."""
    def decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            agent_did = getattr(self, 'tessorium_did', None)
            if not agent_did:
                raise ValueError("Agent must have tessorium_did attribute")

            trust = tessorium.verify(agent_did, min_score)
            print(f"Agent {agent_did} verified with score {trust['score']}")

            try:
                result = func(self, *args, **kwargs)
                tessorium.rate(agent_did, "success", {
                    "reliability": 5,
                    "quality": 4,
                    "speed": 5,
                    "safety": 5
                })
                return result
            except Exception as e:
                tessorium.rate(agent_did, "failure", {
                    "reliability": 2,
                    "quality": 2,
                    "speed": 3,
                    "safety": 5
                })
                raise

        return wrapper
    return decorator


class TrustedAgent(Agent):
    """Agent with built-in trust verification."""

    tessorium_did: str = None
    min_trust_score: int = 70

    def __init__(self, tessorium_did: str, **kwargs):
        super().__init__(**kwargs)
        self.tessorium_did = tessorium_did

        # Verify on initialization
        trust = tessorium.verify(tessorium_did, self.min_trust_score)
        print(f"Agent initialized with trust score: {trust['score']}")


# Usage
researcher = TrustedAgent(
    tessorium_did="did:tessorium:agent:researcher:v1",
    role="Senior Research Analyst",
    goal="Find and analyze relevant information",
    backstory="Expert at finding reliable sources",
    verbose=True
)

writer = TrustedAgent(
    tessorium_did="did:tessorium:agent:writer:v1",
    role="Technical Writer",
    goal="Create clear documentation",
    backstory="Skilled at explaining complex topics",
    verbose=True
)

# Create tasks
research_task = Task(
    description="Research the topic thoroughly",
    agent=researcher,
    expected_output="Comprehensive research findings"
)

writing_task = Task(
    description="Write documentation based on research",
    agent=writer,
    expected_output="Clear technical documentation",
    context=[research_task]
)

# Run crew with trust verification
crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    verbose=2
)

result = crew.kickoff()

NEXT_STEPS

LAST_UPDATED: 2026-02-21EDIT_ON_GITHUB