Core Concepts
This page explains the fundamental concepts that make up the fractal ecosystem. Understanding these concepts will help you build better fractal applications.
Model Context Protocol (MCP)
Model Context Protocol (MCP) is the foundation of fractal. MCP is a protocol that allows AI assistants to interact with external tools and data sources. Fractal extends MCP to support interactive UI components.
Key MCP Concepts
- Tools: Functions that AI assistants can call to perform actions
- Resources: Data sources that AI assistants can read from
- Prompts: Templates that AI assistants can use to generate responses
- Components: Interactive UI elements that can be rendered in chat interfaces
Fractal MCP Servers
A Fractal MCP Server is a specialized MCP server that serves interactive React components as tools. These servers:
- Register React components as MCP tools
- Handle component bundling and optimization
- Provide type safety through introspection
- Support component navigation and state management
Server Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ AI Assistant │ │ Fractal MCP │ │ React │
│ │◄──►│ Server │◄──►│ Components │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Component Tools
A Component Tool is a React component that has been registered as an MCP tool. When an AI assistant calls a component tool:
- The server executes the tool’s handler function
- The handler returns data to the component
- The component is rendered with the data
- The rendered component is displayed in the chat interface
Component Tool Structure
mcpServer.componentTool({
name: "say_hello_personal", // Tool name
description: "Display a greeting", // Tool description
componentPath: "./HelloWorld.tsx", // Component file path
inputSchema: {
// Input validation schema
name: z.string(),
},
handler: async (params) => {
// Data processing function
return { name: params.name };
},
});
The useFractal Hook
The useFractal hook is a React hook that provides components with:
- Data: The result from the tool’s handler function
- Error: Any error that occurred during execution
- Navigate: Function to call other component tools
- Loading State: Information about the current loading state
Hook Usage
import { useFractal } from "@fractal-mcp/composer";
export default function MyComponent() {
const { data, error, navigate, loading } = useFractal<MyDataType>();
if (error) return <div>Error: {error.message}</div>;
if (loading) return <div>Loading...</div>;
if (!data) return <div>No data</div>;
return (
<div>
<h1>Hello, {data.name}!</h1>
<button onClick={() => navigate("other_tool", { id: data.id })}>Next Step</button>
</div>
);
}
Component Navigation
Component Navigation allows components to call other components, creating interactive workflows. When a component calls navigate()
:
- The current component is replaced with the new component
- The new component receives the specified parameters
- The AI assistant can continue the conversation with the new context
Navigation Example
// Component A
export default function ComponentA() {
const { navigate, data } = useFractal<{ userId: string }>();
return <button onClick={() => navigate("show_profile", { userId: data.userId })}>View Profile</button>;
}
// Component B
export default function ComponentB() {
const { data } = useFractal<{ userId: string }>();
return (
<div>
<h1>Profile for user {data.userId}</h1>
{/* Profile content */}
</div>
);
}
Component Bundling
Component Bundling is the process of optimizing React components for production deployment. Bundling:
- Combines component code with dependencies
- Minifies and optimizes the bundle
- Extracts CSS into separate files
- Creates type definitions for TypeScript
Bundle Structure
dist/my-component/
├── index.js # Main component bundle
├── index.css # Extracted CSS
├── manifest.json # Component metadata
└── types.d.ts # TypeScript declarations
Type Safety with Introspection
Server Introspection allows fractal to generate TypeScript types from your running server. This provides:
- Autocomplete: Intelligent suggestions for tool names and parameters
- Compile-time Safety: Catch errors before runtime
- Refactoring Support: Safely rename tools and parameters
- Documentation: Types serve as living documentation
Type Generation
# Generate types from running server
npx fractal-mcp generate -s http://localhost:3100/mcp -o ./fractal-generated
Using Generated Types
import { useFractal } from "@fractal-mcp/composer";
import type { ToolMap } from "../fractal-generated/index.js";
export default function TypeSafeComponent() {
const { navigate } = useFractal<ToolMap>();
return (
<button
onClick={() => {
// TypeScript validates tool name and parameters
navigate("say_hello_personal", { name: "Alice" });
}}
>
Say Hello
</button>
);
}
Registry and Discovery
The Fractal Registry is a centralized service that:
- Stores metadata about fractal servers
- Handles version negotiation
- Provides authentication and authorization
- Enables service discovery
Registry Workflow
- Publishing: Servers register with the registry
- Discovery: Clients query the registry for services
- Resolution: Registry returns server URLs and metadata
- Connection: Clients connect directly to servers
Authentication and Authorization
Fractal supports multiple authentication methods:
- API Keys: Simple key-based authentication
- Bearer Tokens: JWT-based authentication
- OAuth2: Standard OAuth2 flow
- Custom: Custom authentication strategies
Authentication Flow
Client ──API Key──► Registry ──Validate──► Server
│ │
└───────────Direct Connection────────┘
Version Management
Fractal uses Semantic Versioning for managing server versions:
- Major versions: Breaking changes
- Minor versions: New features (backward compatible)
- Patch versions: Bug fixes (backward compatible)
Version Ranges
// Latest version
await createClient("service@latest");
// Specific version
await createClient("service@1.2.3");
// Version range
await createClient("service@^1.0.0");
// Exact version
await createClient("service@=1.2.3");
Error Handling
Fractal provides structured error handling with specific error codes:
- FRACTAL_SERVER_NOT_FOUND: Server not found in registry
- FRACTAL_TOOL_NOT_FOUND: Tool not found on server
- FRACTAL_VALIDATION_ERROR: Invalid input parameters
- FRACTAL_AUTHENTICATION_ERROR: Authentication failed
- FRACTAL_AUTHORIZATION_ERROR: Insufficient permissions
Error Handling Example
try {
const result = await api.someTool(params);
// Handle success
} catch (error) {
switch (error.code) {
case "FRACTAL_VALIDATION_ERROR":
console.error("Invalid parameters:", error.details);
break;
case "FRACTAL_AUTHENTICATION_ERROR":
console.error("Authentication failed");
break;
default:
console.error("Unexpected error:", error.message);
}
}
Observability
Fractal provides built-in observability features:
- Structured Logging: JSON-formatted logs with correlation IDs
- OpenTelemetry Traces: Distributed tracing across services
- Metrics: Performance and usage metrics
- Health Checks: Service health monitoring
Logging Example
// Server-side logging
mcpServer.componentTool({
name: "my_tool",
handler: async (params) => {
logger.info("Processing tool request", {
tool: "my_tool",
params,
correlationId: request.correlationId,
});
// Tool logic...
logger.info("Tool completed successfully", {
tool: "my_tool",
result: "success",
});
},
});
Best Practices
Component Design
- Single Responsibility: Each component should have one clear purpose
- Type Safety: Use TypeScript and generated types
- Error Handling: Handle errors gracefully with user-friendly messages
- Loading States: Show loading indicators for better UX
- Accessibility: Follow accessibility guidelines
Server Design
- Validation: Validate all inputs with Zod schemas
- Error Handling: Provide meaningful error messages
- Logging: Log important events for debugging
- Security: Implement proper authentication and authorization
- Performance: Optimize handlers for fast response times
Client Integration
- Version Pinning: Pin to specific versions in production
- Error Handling: Handle all error cases gracefully
- Connection Pooling: Reuse client instances when possible
- Type Safety: Use generated types for full type safety
- Testing: Write comprehensive tests for your integration
What’s Next?
- Quick Start: Build your first fractal application
- Provider SDK: Learn to build fractal servers
- Consumer SDK: Learn to consume fractal services
- Architecture: Understand system architecture