UUID Generation in AI Agents: Why MCP Matters

"Generate a UUID for this record." A simple request, but one that AI agents get catastrophically wrong. LLMs don't generate UUIDs - they fabricate strings that look like UUIDs but aren't unique, aren't random, and will eventually cause database collisions.

The Problem: LLMs Make Up Fake UUIDs

When you ask an LLM to generate a UUID, it produces something like 550e8400-e29b-41d4-a716-446655440000. This looks correct - right format, right length, proper hyphens. But it's not a real UUID.

LLMs have seen millions of UUIDs in their training data. They've learned the pattern. But they cannot generate randomness. They predict what a UUID should look like based on patterns, often returning the same UUIDs they've seen before or simple variations.

LLM "UUID" vs Real UUID
// Ask an LLM 10 times for UUIDs:
"550e8400-e29b-41d4-a716-446655440000"  // Example from RFC 4122!
"123e4567-e89b-12d3-a456-426614174000"  // Another RFC example!
"f47ac10b-58cc-4372-a567-0e02b2c3d479"  // Seen in many tutorials
// LLMs often return the same "example" UUIDs repeatedly

// Real UUID v4 from TinyFn (actually random):
"7c9e6679-7425-40de-944b-e07fc1f90ae7"
"a1b2c3d4-e5f6-4789-abcd-ef0123456789"
// Each call generates a truly unique value
The RFC 4122 Problem: The UUID 550e8400-e29b-41d4-a716-446655440000 is literally the example UUID from RFC 4122. LLMs have seen it thousands of times and love to return it. If your AI agent uses this as a database primary key, you'll eventually collide with every other system that made the same mistake.

Why This Matters for Production Systems

Database Primary Key Collisions

If an AI agent inserts records with fake UUIDs, you'll eventually get primary key collisions. In the best case, the insert fails. In the worst case, you overwrite existing data.

Distributed Systems Break

UUIDs are designed so that any system can generate them without coordination. If your AI agent produces non-random UUIDs, two systems could generate the same ID for different records.

Security Implications

Predictable UUIDs are a security vulnerability. If an attacker can guess your session tokens or resource IDs, they can potentially access unauthorized data.

Real-World Failure Scenario
// Agent creating orders with "generated" UUIDs
await db.insert('orders', {
  id: llm.generateUUID(),  // Returns "550e8400-e29b..."
  customer: 'Alice',
  total: 99.99
});

// Later, same or different agent...
await db.insert('orders', {
  id: llm.generateUUID(),  // Returns "550e8400-e29b..." again!
  customer: 'Bob',
  total: 149.99
});

// COLLISION! Alice's order is overwritten or insert fails
// Either way, data integrity is compromised

UUID Versions Explained

Before diving into MCP tools, let's understand UUID versions:

UUID v1 (Time-based)

Generated from timestamp and MAC address. Guaranteed unique but reveals when and where it was generated. Useful for sorting by creation time.

UUID v4 (Random)

Generated from cryptographically secure random numbers. 122 bits of randomness. Most commonly used. Reveals no information about creation time or source.

UUID v5 (Name-based)

Generated by hashing a namespace and name with SHA1. Same inputs always produce the same UUID. Useful for deterministic ID generation.

Version Method Use Case
v1 Timestamp + MAC Time-ordered records
v4 Random Most applications (recommended)
v5 SHA1(namespace + name) Deterministic IDs from names

UUID Generation via MCP

TinyFn provides proper UUID generation tools that your AI agent can call via MCP:

Generate UUID v4 (Random)

MCP Tool Call: UUID v4
Tool: generate/uuid
Input: {
  "version": 4
}

Response: {
  "uuid": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
  "version": 4
}

// Each call returns a unique, properly random UUID

Generate UUID v1 (Time-based)

MCP Tool Call: UUID v1
Tool: generate/uuid
Input: {
  "version": 1
}

Response: {
  "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  "version": 1,
  "timestamp": "2025-01-31T10:30:00Z"
}

Generate Multiple UUIDs

MCP Tool Call: Batch UUID Generation
Tool: generate/uuid-batch
Input: {
  "count": 5,
  "version": 4
}

Response: {
  "uuids": [
    "a1b2c3d4-e5f6-4a89-b012-c34567890abc",
    "b2c3d4e5-f6a7-4b89-c012-d45678901bcd",
    "c3d4e5f6-a7b8-4c89-d012-e56789012cde",
    "d4e5f6a7-b8c9-4d89-e012-f67890123def",
    "e5f6a7b8-c9d0-4e89-f012-a78901234ef0"
  ],
  "version": 4,
  "count": 5
}

Validate Existing UUID

MCP Tool Call: Validate UUID
Tool: validate/uuid
Input: {
  "uuid": "550e8400-e29b-41d4-a716-446655440000"
}

Response: {
  "valid": true,
  "version": 4,
  "variant": "RFC4122",
  "uuid": "550e8400-e29b-41d4-a716-446655440000"
}

// Note: The UUID is valid format, but if it came from an LLM,
// it's likely not unique - validation only checks format

Database Workflows with AI Agents

Here's how to properly handle UUIDs in AI agent database workflows:

Creating Records

Correct Record Creation
// Agent workflow for creating a new user

1. User request: "Create account for alice@example.com"

2. Agent calls MCP tool:
   Tool: generate/uuid
   Input: { "version": 4 }
   Result: { "uuid": "7c9e6679-7425-40de-944b-e07fc1f90ae7" }

3. Agent creates record:
   INSERT INTO users (id, email, created_at)
   VALUES ('7c9e6679-7425-40de-944b-e07fc1f90ae7',
           'alice@example.com',
           NOW());

4. Agent confirms: "Created account with ID 7c9e6679..."

Batch Operations

Batch Insert with UUIDs
// Agent importing multiple products

1. Agent determines need for 100 UUIDs

2. Agent calls batch tool:
   Tool: generate/uuid-batch
   Input: { "count": 100, "version": 4 }
   Result: { "uuids": ["uuid1", "uuid2", ...] }

3. Agent maps UUIDs to products:
   products.forEach((product, i) => {
     product.id = uuids[i];
   });

4. Agent performs batch insert with unique IDs

Implementation Guide

The right way to give your AI agent proper UUID generation is to connect it to TinyFn via MCP. This lets the LLM automatically discover and call UUID tools without you implementing any custom API logic.

pydantic-ai with TinyFn MCP
from pydantic_ai import Agent, MCPServerTool

# Create an agent with TinyFn MCP tools
agent = Agent(
    'anthropic:claude-sonnet-4-5',
    builtin_tools=[
        MCPServerTool(
            id='tinyfn',
            url='https://api.tinyfn.io/mcp/all/',
            headers={'X-API-Key': 'your-api-key'},
            description='500+ deterministic tools including UUID generation',
        )
    ],
    system_prompt="""You are a database assistant.
When creating records that need unique IDs, ALWAYS use the generate/uuid
tool to create proper UUIDs. Never make up IDs yourself."""
)

# The agent automatically uses MCP tools for UUID generation
result = agent.run_sync('Create a new user record for alice@example.com')
print(result.output)
# "Created user with ID 7c9e6679-7425-40de-944b-e07fc1f90ae7"

# Works for batch operations too
result = agent.run_sync('Generate IDs for 5 new products')
print(result.output)
# Returns 5 unique, valid UUIDs from the generate/uuid-batch tool
Vercel AI SDK with TinyFn MCP
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';

// Connect to TinyFn MCP server
const result = await generateText({
  model: openai('gpt-4o'),
  system: `You are a database assistant.
When creating records that need unique IDs, ALWAYS use the generate/uuid
tool to create proper UUIDs. Never make up IDs yourself.`,
  prompt: 'Create a new user record for alice@example.com',
  tools: {
    tinyfn: openai.tools.mcp({
      serverLabel: 'tinyfn',
      serverUrl: 'https://api.tinyfn.io/mcp/all/',
      serverDescription: '500+ deterministic tools including UUID generation',
      headers: { 'X-API-Key': 'your-api-key' },
    }),
  },
});

console.log(result.text);
// "Created user with ID 7c9e6679-7425-40de-944b-e07fc1f90ae7"

// Or use the MCP client directly for more control
import { createMCPClient } from '@ai-sdk/mcp';

const mcpClient = await createMCPClient({
  transport: {
    type: 'http',
    url: 'https://api.tinyfn.io/mcp/all/',
    headers: { 'X-API-Key': 'your-api-key' },
  },
});

const tools = await mcpClient.tools();

const response = await generateText({
  model: openai('gpt-4o'),
  tools,
  prompt: 'Generate 10 UUIDs for a batch product import',
});

await mcpClient.close();

Using MCP with Claude Desktop or Cursor

If you're using Claude Desktop, Cursor, or another MCP-compatible client, add TinyFn to your MCP configuration:

MCP Configuration (claude_desktop_config.json)
{
  "mcpServers": {
    "tinyfn": {
      "url": "https://api.tinyfn.io/mcp/all/",
      "headers": {
        "X-API-Key": "your-api-key"
      }
    }
  }
}

Once configured, the AI will automatically use the generate/uuid tool whenever it needs to create unique identifiers for database records, API responses, or file naming.

Why Agent Frameworks Beat Manual Implementation

  • Automatic tool discovery: The LLM sees all available tools and picks generate/uuid when appropriate
  • No manual mapping: You don't write code for each UUID version or batch operation
  • Better reasoning: The LLM can chain UUID generation with other tools (e.g., validate then insert)
  • Always correct: Real cryptographic randomness, not pattern-matched guesses
Key Insight: You don't build "UUID generation" into your agent. You configure MCP once, and the agent gains the ability to generate real UUIDs whenever needed. The same applies to all 500+ TinyFn tools - math, validation, conversion, hashing, and more.

Best Practices

  1. Never trust LLM-generated UUIDs: Always use MCP tools or server-side generation. LLMs cannot generate random values.
  2. Use UUID v4 by default: Random UUIDs are best for most applications. Use v1 only if you need timestamp ordering.
  3. Validate format, not uniqueness: Validation tools check format only. Uniqueness comes from proper generation.
  4. Batch generate when possible: If inserting many records, generate all UUIDs in one API call to reduce latency.
  5. Store as native UUID type: Most databases have native UUID types. Use them for better indexing and storage efficiency.
  6. Consider ULIDs for sorting: If you need sortable IDs, consider ULID (Universally Unique Lexicographically Sortable Identifier) tools.

Generate Real UUIDs in Your AI Agent

Stop using fake UUIDs. Get your free TinyFn API key and generate proper UUIDs via MCP.

Get Free API Key

Ready to try TinyFn?

Get your free API key and start building in minutes.

Get Free API Key