---
title: "Server Architecture"
description: "Deep dive into the IBM i MCP Server architecture, including the 'Logic Throws, Handler Catches' pattern, component interactions, and lifecycle management."
---
# Server Architecture
The IBM i MCP Server follows a carefully designed architecture that ensures modularity, testability, and operational clarity through strict separation of concerns. This guide explores the core architectural patterns and component interactions.
<Note>
The architecture is built around the **"Logic Throws, Handler Catches"** principle, which forms the foundation of our error-handling and control-flow strategy.
</Note>
## Core Architectural Principles
### 1. Logic Throws, Handler Catches
This immutable pattern ensures clean separation between business logic and transport handling:
<Tabs>
<Tab title="Logic Layer (logic.ts)">
**Responsibilities:**
- Execute pure business logic
- Remain stateless and self-contained
- Terminate by throwing structured `McpError` on failure
- Never contain try...catch blocks for response formatting
```typescript
// Example from catFactFetcher/logic.ts
export async function catFactFetcherLogic(
params: CatFactFetcherInput,
): Promise<CatFactFetcherResponse> {
// Pure business logic execution
if (params.message === "fail") {
throw new McpError(
BaseErrorCode.VALIDATION_ERROR,
"Deliberate failure triggered",
{ toolName: "cat_fact_fetcher" }
);
}
return processedResult;
}
```
</Tab>
<Tab title="Handler Layer (registration.ts)">
**Responsibilities:**
- Interface with transport layer (MCP, HTTP)
- Wrap logic calls in try...catch blocks
- Format responses using `ErrorHandler`
- Manage final response lifecycle
```typescript
// Example from catFactFetcher/registration.ts
async (params: CatFactFetcherInput) => {
try {
const result = await catFactFetcherLogic(params, context);
return {
structuredContent: result,
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
};
} catch (error) {
const mcpError = ErrorHandler.handleError(error, { context });
return {
isError: true,
content: [{ type: "text", text: `Error: ${mcpError.message}` }]
};
}
}
```
</Tab>
</Tabs>
### 2. Structured Request Context
Every operation maintains traceability through structured logging:
```typescript
const context = requestContextService.createRequestContext({
operation: "HandleToolRequest",
toolName: TOOL_NAME,
input: params,
});
```
## Application Architecture Overview
```mermaid
graph TB
subgraph "Entry Point"
A[src/index.ts] --> B[initializeAndStartServer]
end
subgraph "Server Orchestration"
B --> C[src/mcp-server/server.ts]
C --> D[createMcpServerInstance]
C --> E[startTransport]
end
subgraph "Transport Layer"
E --> F[stdio Transport]
E --> G[HTTP Transport]
F --> H[StdioServerTransport]
G --> I[StreamableHTTPServerTransport]
end
subgraph "MCP Core"
D --> J[McpServer Instance]
J --> K[registerAllResources]
J --> L[registerSQLTools]
J --> M[registerAllTools]
end
subgraph "Tool System"
M --> N[Tool Registration]
N --> O[Handler Functions]
O --> P[Logic Functions]
end
subgraph "IBM i Integration"
L --> Q[YAML Configuration]
Q --> R[SQL Tool Engine]
R --> S[Mapepire/DB2i Connection]
end
style A fill:#e1f5fe
style J fill:#f3e5f5
style P fill:#e8f5e8
style S fill:#fff3e0
```
## Server Startup Sequence
The application follows a precise startup sequence ensuring all components are properly initialized:
```mermaid
sequenceDiagram
participant Entry as src/index.ts
participant Server as server.ts
participant MCP as McpServer
participant Tools as Tool Registration
participant Transport as Transport Layer
Entry->>Entry: Parse CLI arguments
Entry->>Entry: Apply configuration overrides
Entry->>Server: initializeAndStartServer()
Server->>Server: createMcpServerInstance()
Server->>MCP: new McpServer(config, capabilities)
Server->>Tools: registerAllResources(server)
Tools-->>MCP: server.registerResource()
Server->>Tools: registerSQLTools(server)
Tools-->>MCP: server.registerTool() [YAML tools]
Server->>Tools: registerAllTools(server)
Tools-->>MCP: server.registerTool() [TypeScript tools]
Server->>Transport: startTransport()
alt HTTP Transport
Transport->>Transport: startHttpTransport()
Transport-->>Server: HTTP Server instance
else STDIO Transport
Transport->>Transport: startStdioTransport()
Transport-->>Server: McpServer instance
end
Server-->>Entry: Running server instance
Entry->>Entry: Setup signal handlers
```
<Note>
**Key Architectural Decision**: The startup sequence registers ALL tools during initialization, not on-demand. This ensures consistent tool availability and enables proper error handling during startup rather than runtime failures.
</Note>
## Tool Execution Flow
Every tool follows the same execution pattern, ensuring consistency and reliability:
```mermaid
graph TB
subgraph "Client Request"
A[MCP Client] --> B[Transport Layer]
end
subgraph "MCP Server Processing"
B --> C[McpServer.invokeHandler]
C --> D[Input Schema Validation]
D --> E[Handler Function]
end
subgraph "Handler Layer (registration.ts)"
E --> F[Create RequestContext]
F --> G[try block starts]
G --> H[Call Logic Function]
H --> I[Format Success Response]
G --> J[catch block]
J --> K[ErrorHandler.handleError]
K --> L[Format Error Response]
end
subgraph "Logic Layer (logic.ts)"
H --> M[Pure Business Logic]
M --> N{Success?}
N -->|Yes| O[Return Result]
N -->|No| P[throw McpError]
O --> I
P --> J
end
subgraph "Response Path"
I --> Q[CallToolResult]
L --> Q
Q --> R[Transport Response]
R --> S[Client Response]
end
style E fill:#e3f2fd
style M fill:#e8f5e8
style P fill:#ffebee
style K fill:#fff3e0
```
## Component Architecture
### Tool Development Structure
Each tool follows a mandated three-file structure that enforces the architectural patterns:
```mermaid
graph LR
subgraph "Tool Directory: src/mcp-server/tools/toolName/"
A[index.ts<br/>Barrel Export] --> B[registration.ts<br/>Handler Layer]
B --> C[logic.ts<br/>Business Logic]
end
subgraph "External Dependencies"
C --> D[External APIs]
C --> E[Database Services]
C --> F[Utility Functions]
end
subgraph "Core Infrastructure"
B --> G[ErrorHandler]
B --> H[RequestContext]
B --> I[MCP Server]
end
style A fill:#f0f0f0
style B fill:#e3f2fd
style C fill:#e8f5e8
style G fill:#fff3e0
```
### SQL Tools Architecture
IBM i-specific SQL tools use a YAML-driven approach for rapid development:
```mermaid
graph TB
subgraph "YAML Configuration"
A[prebuiltconfigs/*.yaml] --> B[ToolProcessor]
B --> C[Schema Generation]
B --> D[Tool Registration]
end
subgraph "Runtime Execution"
E[Client Request] --> F[YAML Tool Handler]
F --> G[Parameter Validation]
G --> H[SQL Security Check]
H --> I[YamlSqlExecutor]
end
subgraph "IBM i Integration"
I --> J[Connection Pool Manager]
J --> K[Mapepire Client]
K --> L[DB2i Database]
end
subgraph "Response Processing"
L --> M[Result Formatting]
M --> N[Security Audit]
N --> O[Response Delivery]
end
style A fill:#fff8e1
style E fill:#e3f2fd
style L fill:#e8f5e8
style N fill:#ffebee
```
## Error Handling Architecture
The error handling system provides comprehensive coverage while maintaining system stability:
```mermaid
graph TB
subgraph "Error Sources"
A[Logic Layer Errors] --> E[McpError Thrown]
B[External API Failures] --> E
C[Database Errors] --> E
D[Validation Failures] --> E
end
subgraph "Error Processing"
E --> F[Handler Catch Block]
F --> G[ErrorHandler.handleError]
G --> H[Error Classification]
G --> I[Structured Logging]
G --> J[Error Formatting]
end
subgraph "Error Response"
J --> K[CallToolResult with isError]
K --> L[Transport Layer]
L --> M[Client Error Response]
end
subgraph "System Protection"
G --> N[Rate Limiting]
G --> O[Circuit Breaker]
G --> P[Graceful Degradation]
end
style E fill:#ffebee
style G fill:#fff3e0
style N fill:#f3e5f5
```
## Authentication & Security Architecture
The server supports multiple authentication modes with integrated IBM i security:
```mermaid
graph TB
subgraph "Authentication Modes"
A[MCP_AUTH_MODE=none] --> E[No Authentication]
B[MCP_AUTH_MODE=jwt] --> F[JWT Validation]
C[MCP_AUTH_MODE=oauth] --> G[OAuth/OIDC]
D[MCP_AUTH_MODE=ibmi] --> H[IBM i HTTP Auth]
end
subgraph "IBM i Authentication Flow"
H --> I[RSA Key Pair]
I --> J[Encrypted Credential Exchange]
J --> K[IBM i User Profile Validation]
K --> L[Authority Checking]
end
subgraph "Authorization Layer"
F --> M[Scope Validation]
G --> M
L --> N[IBM i Authority Integration]
M --> O[Tool Access Control]
N --> O
end
subgraph "Audit & Compliance"
O --> P[Audit Logging]
P --> Q[Security Events]
Q --> R[Compliance Reporting]
end
style H fill:#e8f5e8
style K fill:#fff3e0
style P fill:#f3e5f5
```
## Transport Layer Architecture
The server supports both development and production transport modes:
<Tabs>
<Tab title="STDIO Transport">
**Use Cases:**
- CLI tools and MCP Inspector
- Direct process communication
- Development and testing
```mermaid
graph LR
A[MCP Client Process] <--> B[stdin/stdout]
B <--> C[StdioServerTransport]
C <--> D[McpServer Instance]
D <--> E[Tool Handlers]
```
</Tab>
<Tab title="HTTP Transport">
**Use Cases:**
- Web applications and REST APIs
- Production deployments
- Load balancing and scaling
```mermaid
graph LR
A[HTTP Client] --> B[HTTP Request]
B --> C[StreamableHTTPServerTransport]
C --> D[Session Management]
D --> E[McpServer Instance]
E --> F[Tool Handlers]
F --> G[Server-Sent Events]
G --> H[HTTP Response]
```
</Tab>
</Tabs>
## Observability & Monitoring
The architecture includes comprehensive observability features:
```mermaid
graph TB
subgraph "Request Tracing"
A[RequestContext Creation] --> B[Unique Request ID]
B --> C[Context Propagation]
C --> D[Structured Logging]
end
subgraph "OpenTelemetry Integration"
D --> E[Trace Collection]
E --> F[Metrics Aggregation]
F --> G[OTLP Export]
end
subgraph "Monitoring Outputs"
G --> H[Jaeger Tracing]
G --> I[Prometheus Metrics]
G --> J[Custom Dashboards]
end
subgraph "Operational Intelligence"
D --> K[Error Rate Monitoring]
D --> L[Performance Metrics]
D --> M[Business Intelligence]
end
style A fill:#e8f5e8
style E fill:#e3f2fd
style K fill:#fff3e0
```
## Best Practices & Patterns
<AccordionGroup>
<Accordion title="Tool Development Guidelines" icon="code">
- **Logic Purity**: Keep business logic functions pure and stateless
- **Error Throwing**: Always throw `McpError` for failures in logic layer
- **Handler Wrapping**: Every logic call must be wrapped in try...catch in handlers
- **Context Propagation**: Pass `RequestContext` through the entire call stack
- **Schema Validation**: Define comprehensive Zod schemas for inputs and outputs
</Accordion>
<Accordion title="YAML SQL Tool Patterns" icon="database">
- **Parameter Security**: Use parameter binding to prevent SQL injection
- **Authority Checking**: Include appropriate IBM i authority requirements
- **Result Limiting**: Always include row limits for large result sets
- **Audit Logging**: Mark sensitive operations with `security.audit: true`
- **Performance Consideration**: Design queries for production system impact
</Accordion>
<Accordion title="Error Handling Standards" icon="exclamation-triangle">
- **Structured Errors**: Always use `McpError` with appropriate error codes
- **Context Inclusion**: Include relevant context in error details
- **No Silent Failures**: Every error must be logged and handled
- **Graceful Degradation**: Provide meaningful fallback behaviors
- **Client Communication**: Return user-friendly error messages
</Accordion>
<Accordion title="Security Implementation" icon="shield-check">
- **Input Validation**: Validate all inputs with Zod schemas
- **Authorization Checks**: Verify scope requirements for sensitive operations
- **IBM i Integration**: Leverage IBM i's built-in security model
- **Audit Trails**: Maintain comprehensive audit logs
- **Credential Management**: Use environment variables for sensitive data
</Accordion>
</AccordionGroup>
## Integration Points
The architecture provides multiple integration points for extending functionality:
<CardGroup cols={2}>
<Card title="Custom SQL Tools" icon="wrench" href="/sql-tools/building-tools">
Extend functionality with YAML SQL configurations for IBM i database operations
</Card>
<Card title="Agent Development" icon="robot" href="/agents/building-agents">
Build AI agents that understand the server architecture and IBM i concepts
</Card>
<Card title="Authentication Providers" icon="key" href="/api/auth-endpoints">
Implement custom authentication modes and IBM i security integration
</Card>
<Card title="Production Deployment" icon="chart-line" href="/deployment/production">
Connect observability data to enterprise monitoring and alerting systems
</Card>
</CardGroup>
<Note>
For complete configuration details including environment variables for each architectural component, see the [Configuration Reference](/configuration).
</Note>
<Note>
**Architectural Philosophy**: The "Logic Throws, Handler Catches" pattern ensures that business logic remains testable and pure, while handlers manage the complexity of transport protocols and error formatting. This separation enables reliable unit testing and makes the system easier to maintain and extend.
</Note>
<Note>
This architecture has been battle-tested in enterprise IBM i environments and follows industry best practices for production MCP server deployment. The modular design ensures that each component can be developed, tested, and maintained independently while working together as a cohesive system.
</Note>