# AI Universe MCP Conversation Client

TypeScript client library for the AI Universe Conversation MCP Server with unified auto-creation API.

## Installation

```bash
npm install @ai-universe/mcp-conversation-client
```

## Features

- 🚀 **Unified Auto-Creation API** - Conversations auto-create on first message
- 📝 **Type-Safe** - Full TypeScript support with exported types
- 🔒 **Secure** - Built-in userId validation and ownership checks
- 📊 **Complete API Coverage** - All 4 MCP conversation tools supported
- 🎯 **Simple & Intuitive** - Clean, easy-to-use API
- ✅ **Persist-or-Error Contract** - v2.0.4+ guarantees every successful `sendMessage`
  returns both `conversationId` and `messageId`, and the client throws if either is missing

## Persist-or-Error Guarantee

Beginning with v2.0.4 the Conversation MCP server retries transient Firestore failures once
and only returns success when both the conversation and message records have been
persisted. The TypeScript client enforces this contract: if a response omits either
identifier it throws, ensuring agents never operate on partially saved data. Remove any
synthetic persistence fallbacks in your agents once you upgrade to this release.

## Quick Start

```typescript
import { ConversationClient } from '@ai-universe/mcp-conversation-client';

// Initialize client
const client = new ConversationClient('http://localhost:3000/mcp');

// Send a message (auto-creates conversation if needed)
const result = await client.sendMessage({
  userId: 'user_123',
  content: 'Hello! This is my first message.',
  role: 'user',
  title: 'My Conversation'
});

console.log('Conversation ID:', result.conversationId);
console.log('Created new conversation:', result.created);

// Add another message to the same conversation
await client.sendMessage({
  userId: 'user_123',
  conversationId: result.conversationId,
  content: 'This is my second message.',
  role: 'assistant'
});

// Get conversation metadata
const conversation = await client.getConversation({
  userId: 'user_123',
  conversationId: result.conversationId
});

console.log('Title:', conversation.title);
console.log('Message count:', conversation.messageCount);

// Get message history
const history = await client.getHistory({
  userId: 'user_123',
  conversationId: result.conversationId,
  limit: 50
});

console.log('Messages:', history.messages);

// List all conversations for a user
const conversations = await client.listConversations({
  userId: 'user_123',
  pageSize: 10
});

console.log('Total conversations:', conversations.totalCount);
```

## API Reference

### `sendMessage(params)`

Send a message to a conversation. Auto-creates conversation if `conversationId` is not provided.

**Parameters:**
- `userId` (string, required) - User identifier
- `content` (string, required) - Message content
- `role` ('user' | 'assistant', required) - Message role
- `conversationId` (string, optional) - Conversation ID. Omit to auto-create.
- `title` (string, optional) - Conversation title (only used on auto-creation)

**Returns:**
```typescript
{
  conversationId: string;
  messageId: string;
  sequence: number;
  created: boolean;  // true if conversation was auto-created
  title: string;
  timestamp: string; // ISO-8601 timestamp of message creation
}
```

### `getConversation(params)`

Get conversation metadata.

**Parameters:**
- `userId` (string, required)
- `conversationId` (string, required)

**Returns:**
```typescript
{
  conversationId: string;
  userId: string;
  title: string;
  messageCount: number;
  createdAt: string;
  updatedAt: string;
}
```

### `getHistory(params)`

Get conversation message history with pagination.

**Parameters:**
- `userId` (string, required)
- `conversationId` (string, required)
- `limit` (number, optional) - Max messages to return
- `cursor` (string, optional) - Pagination cursor

**Returns:**
```typescript
{
  conversationId: string;
  messages: Array<{
    messageId: string;
    conversationId: string;
    content: string;
    role: 'user' | 'assistant';
    sequence: number;
    timestamp: string;
  }>;
  hasMore: boolean;
  nextCursor?: string;
}
```

### `listConversations(params)`

List all conversations for a user with pagination.

**Parameters:**
- `userId` (string, required)
- `pageSize` (number, optional) - Conversations per page
- `cursor` (string, optional) - Pagination cursor

**Returns:**
```typescript
{
  conversations: Array<{
    conversationId: string;
    title: string;
    messageCount: number;
    createdAt: string;
    updatedAt: string;
  }>;
  totalCount: number;
  hasMore: boolean;
  nextCursor?: string;
}
```

## Auto-Creation Feature

The unified API automatically creates conversations when you send the first message without providing a `conversationId`:

```typescript
// First message - auto-creates conversation
const result = await client.sendMessage({
  userId: 'user_123',
  content: 'Hello!',
  role: 'user',
  title: 'My Chat'  // Optional title
});

console.log(result.created);  // true
console.log(result.conversationId);  // Auto-generated ID

// Subsequent messages - use the conversation ID
await client.sendMessage({
  userId: 'user_123',
  conversationId: result.conversationId,
  content: 'Follow-up message',
  role: 'assistant'
});
```

If no title is provided, one is auto-generated from the first message content with PII redaction.

## Error Handling

```typescript
try {
  const result = await client.sendMessage({
    userId: 'user_123',
    content: 'Hello!',
    role: 'user'
  });
} catch (error) {
  if (error.message.includes('unauthorized')) {
    console.error('User does not own this conversation');
  } else if (error.message.includes('not found')) {
    console.error('Conversation not found');
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Types

All types are exported for use in your application:

```typescript
import type {
  SendMessageParams,
  SendMessageResponse,
  GetConversationParams,
  ConversationMetadata,
  GetHistoryParams,
  ConversationHistory,
  ListConversationsParams,
  ConversationList,
  Message
} from '@ai-universe/mcp-conversation-client';
```

## JSON Schemas

Starting in v2.1.0, comprehensive JSON schemas are included for all MCP tool requests and responses. These can be used for validation, documentation, code generation, and more.

### Using the Schemas

```typescript
// Import all schemas
import { schemas, requestSchemas, responseSchemas } from '@ai-universe/mcp-conversation-client/schemas';

// Use individual schemas
import {
  sendMessageRequestSchema,
  sendMessageResponseSchema,
  getHistoryRequestSchema,
  getHistoryResponseSchema
} from '@ai-universe/mcp-conversation-client/schemas';
```

### Available Schemas

Request and response schemas are available for all MCP tools:

- `health-check` - Health check endpoint
- `convo.send-message` - Send message with auto-creation
- `convo.get-conversation` - Get conversation metadata
- `convo.get-history` - Get conversation history
- `convo.get-message` - Get a single message
- `convo.list-conversations` - List user conversations

### Schema Structure

All schemas are JSON Schema Draft 7 compliant. Example:

```typescript
// Access a complete tool schema
const sendMessageSchema = schemas['convo.send-message'];
console.log(sendMessageSchema.request);   // Request schema
console.log(sendMessageSchema.response);  // Response schema

// Or access directly
console.log(requestSchemas['convo.send-message']);
console.log(responseSchemas['convo.send-message']);
```

### Validation Example

Use with your favorite JSON Schema validator:

```typescript
import Ajv from 'ajv';
import { sendMessageRequestSchema } from '@ai-universe/mcp-conversation-client/schemas';

const ajv = new Ajv();
const validate = ajv.compile(sendMessageRequestSchema);

const data = {
  userId: 'user_123',
  content: 'Hello!',
  role: 'user'
};

if (validate(data)) {
  console.log('Valid!');
} else {
  console.log('Invalid:', validate.errors);
}
```

## Version History

### 2.1.0 (Current)
- ✨ **NEW:** Comprehensive JSON schemas for all MCP tool requests and responses
- Export schemas separately via `@ai-universe/mcp-conversation-client/schemas`
- JSON Schema Draft 7 compliant for validation, documentation, and code generation
- All previous v2.0.x features included

### 2.0.6
- Unified auto-creation API
- Complete TypeScript support
- PII redaction in auto-generated titles
- Firestore backend support
- Persist-or-Error contract guarantee

### 1.x
- Legacy in-memory storage
- Manual conversation creation required

## License

MIT

## Support

For issues and questions:
- GitHub: [ai_universe_convo_mcp](https://github.com/jleechanorg/ai_universe_convo_mcp)
- Issues: [GitHub Issues](https://github.com/jleechanorg/ai_universe_convo_mcp/issues)
