# @agforge/engine

DefaultAgent with built-in interceptors, MCP client, tool factory, context compression, and error hierarchy — the capability layer of [AgForge SDK](https://github.com/ai-agforge/agforge-sdk).

## Overview

`@agforge/engine` provides the full implementation on top of `@agforge/core`:

- **DefaultAgent** — production-ready agent with auto-assembled built-in interceptors
- **Built-in interceptors** — tracing, compression, error limits, message sanitization, system reminder, MCP, and more
- **MCP client** — full Model Context Protocol integration with auto-reconnect, heartbeat, and circuit breaker
- **Tool factory** — `createTool` with Zod schema validation and dual-channel output
- **Context compression** — threshold-based strategy + LLM summary compressor
- **Message sanitization** — auto-fix rules for malformed message sequences
- **Error hierarchy** — structured error types for agent lifecycle
- **Execution locker** — per-tool serial locking for concurrent safety
- **Permission manager** — URL-based permission control
- **Skill system** — declarative skill composition
- **System reminder** — automatic system prompt injection

## Install

```bash
npm install @agforge/engine
# or
pnpm add @agforge/engine
```

## Usage

### Basic Agent

```typescript
import { DefaultAgent } from '@agforge/engine';
import { AiModel } from '@agforge/models';

const agent = new DefaultAgent({ model, tools: [] });

for await (const _ of agent.execute({
  message: [{ type: 'text', text: 'Hello!' }],
})) {}
```

### Creating Tools

```typescript
import { createTool } from '@agforge/engine';
import { z } from 'zod';

const weatherTool = createTool({
  name: 'get_weather',
  description: 'Get the current weather for a given city.',
  parameters: z.object({
    city: z.string().describe('The city name'),
  }),
})(() => ({
  execute: async function* (params) {
    const data = await fetchWeather(params.city);
    yield {
      structResult: { temperature: data.temp, humidity: data.humidity },
      llmMessage: { type: 'text', text: `${params.city}: ${data.temp}°C` },
      isCompleted: true,
    };
  },
  stop: async () => {},
}));
```

### MCP Integration

```typescript
import { McpClient } from '@agforge/engine';

const client = new McpClient({
  name: 'my-mcp-server',
  transport: {
    type: 'stdio',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
  },
  reconnect: { enabled: true, maxAttempts: 5 },
});

await client.connect();
const agent = new DefaultAgent({ model, tools: [], mcpClients: [client] });
```

### Context Compression

```typescript
import { ThresholdCompressionStrategy, LlmSummaryCompressor } from '@agforge/engine';

const agent = new DefaultAgent({
  model,
  tools: [],
  compression: {
    compressor: new LlmSummaryCompressor({ model: summaryModel }),
    strategy: new ThresholdCompressionStrategy({
      asyncThreshold: 0.5,
      syncThreshold: 0.7,
      preserveRecentRounds: 5,
    }),
  },
});
```

### Message Sanitization

```typescript
const agent = new DefaultAgent({
  model,
  tools: [],
  messageSanitize: 'fix', // 'fix' (default) | 'warn' | 'off'
});
```

## Related Packages

| Package | Role |
|---------|------|
| [`@agforge/core`](https://github.com/ai-agforge/agforge-sdk/tree/main/packages/core) | Agent protocol, interfaces, execution skeleton |
| [`@agforge/models`](https://github.com/ai-agforge/agforge-sdk/tree/main/packages/models) | LLM provider adapters (Vercel AI SDK v6) |
| [`@agforge/logger`](https://github.com/ai-agforge/agforge-sdk/tree/main/packages/logger) | Hierarchical logging with scoped config |
| [`@agforge/utils`](https://github.com/ai-agforge/agforge-sdk/tree/main/packages/utils) | Shared utilities (CircuitBreaker, sleep, timeout, etc.) |

## License

ISC
