# @layer7/n8n-tanss-api

Modular, reusable MCP-compatible TANSS API tool for n8n AI Agent with comprehensive German UI support.

## Overview

This tool provides a complete integration of the TANSS API for n8n AI Agents, enabling professional automation and intelligent ticket management. Built with MCP (Model Context Protocol) compatibility, it offers dynamic command discovery, comprehensive error handling, and seamless AI agent integration.

## Features

### 🤖 AI Agent Integration
- **MCP-compatible**: Full Model Context Protocol support for AI agents
- **Dynamic command discovery**: Automatic endpoint detection from OpenAPI specification
- **Context-aware suggestions**: AI agents can suggest relevant actions based on current context
- **Introspectable schemas**: Machine-readable command and parameter schemas
- **Agent-friendly naming**: Commands follow `tanss.{resource}.{operation}` pattern

### 🔧 Core Capabilities
- **Complete API coverage**: All TANSS API endpoints supported
- **Resource modules**: Tickets, companies, employees, devices, contracts, and more
- **Authentication**: Bearer token and username/password support
- **Parameter validation**: OpenAPI schema-based validation
- **Error handling**: Comprehensive 4xx/5xx, network, and parsing error handling
- **Optional parameters**: Filter, pagination, sorting, field selection

### 🛠️ Usage Modes
- **CLI mode**: Manual debugging and testing
- **n8n GUI**: Visual configuration in n8n interface
- **Direct embedding**: Agent-prompt integration
- **MCP server**: Standalone MCP server for AI agents

## Installation

```bash
npm install @layer7/n8n-tanss-api
```

## Quick Start

### AI Agent Usage

```javascript
// Direct agent integration
const result = await agent.call('tanss.tickets.list', { 
  status: 'open',
  limit: 10 
});

// Create a new ticket
await agent.call('tanss.tickets.create', {
  title: 'System Issue',
  description: 'Server not responding',
  priority: 'high'
});

// Search companies
const companies = await agent.call('tanss.companies.list', {
  search: 'Acme Corp'
});
```

### CLI Usage

```bash
# List available commands
tanss-cli list-commands

# Execute a command
tanss-cli call tanss.tickets.list --params '{"status":"open"}'

# Get command schema
tanss-cli schema tanss.tickets.create

# Test connection
tanss-cli test --url https://your-tanss.com --token your-token

# Interactive mode
tanss-cli interactive
```

### n8n Configuration

1. **Add Credentials**:
   - Go to n8n Credentials
   - Add "TANSS API" credential
   - Configure:
     - Server URL: `https://your-tanss-server.com`
     - Authentication: Bearer Token or Username/Password
     - Token/Credentials: Your TANSS API credentials

2. **Use in Workflows**:
   - Add "TANSS AI Agent" node
   - Select your credential
   - Choose operation (List Tickets, Create Company, etc.)
   - Configure parameters

### MCP Server

```bash
# Start MCP server
npm run mcp:server

# Or programmatically
import { TanssMCPServer } from '@layer7/n8n-tanss-api';

const server = new TanssMCPServer({
  url: 'https://your-tanss.com',
  token: 'your-token'
});

await server.start();
```

## API Reference

### Available Resources

#### Tickets
- `tanss.tickets.list` - List tickets with filtering
- `tanss.tickets.get` - Get ticket by ID
- `tanss.tickets.create` - Create new ticket
- `tanss.tickets.update` - Update existing ticket
- `tanss.tickets.delete` - Delete ticket

#### Companies
- `tanss.companies.list` - List companies
- `tanss.companies.get` - Get company by ID
- `tanss.companies.create` - Create new company
- `tanss.companies.update` - Update company
- `tanss.companies.delete` - Delete company

#### Employees
- `tanss.employees.list` - List employees
- `tanss.employees.get` - Get employee by ID
- `tanss.employees.create` - Create new employee
- `tanss.employees.update` - Update employee
- `tanss.employees.delete` - Delete employee

#### Devices
- `tanss.devices.list` - List devices
- `tanss.devices.get` - Get device by ID
- `tanss.devices.create` - Create new device
- `tanss.devices.update` - Update device
- `tanss.devices.delete` - Delete device

#### Contracts
- `tanss.contracts.list` - List contracts
- `tanss.contracts.get` - Get contract by ID
- `tanss.contracts.create` - Create new contract
- `tanss.contracts.update` - Update contract
- `tanss.contracts.delete` - Delete contract

### Command Parameters

All commands support standard parameters:

```typescript
interface BaseParameters {
  // Pagination
  limit?: number;
  offset?: number;
  
  // Filtering
  filter?: Record<string, any>;
  search?: string;
  
  // Field selection
  fields?: string[];
  
  // Sorting
  sort?: string;
  order?: 'asc' | 'desc';
}
```

### Example Schemas

#### List Tickets
```json
{
  "name": "tanss.tickets.list",
  "description": "List tickets with optional filtering and pagination",
  "inputSchema": {
    "type": "object",
    "properties": {
      "status": {
        "type": "string",
        "description": "Filter by ticket status",
        "enum": ["open", "closed", "pending"]
      },
      "priority": {
        "type": "string",
        "description": "Filter by priority level",
        "enum": ["low", "medium", "high", "urgent"]
      },
      "limit": {
        "type": "number",
        "description": "Maximum number of results",
        "default": 50
      },
      "offset": {
        "type": "number",
        "description": "Number of results to skip",
        "default": 0
      }
    }
  }
}
```

#### Create Ticket
```json
{
  "name": "tanss.tickets.create",
  "description": "Create a new support ticket",
  "inputSchema": {
    "type": "object",
    "properties": {
      "title": {
        "type": "string",
        "description": "Ticket title",
        "required": true
      },
      "description": {
        "type": "string",
        "description": "Detailed description of the issue",
        "required": true
      },
      "priority": {
        "type": "string",
        "description": "Priority level",
        "enum": ["low", "medium", "high", "urgent"],
        "default": "medium"
      },
      "companyId": {
        "type": "number",
        "description": "ID of the company this ticket belongs to"
      }
    },
    "required": ["title", "description"]
  }
}
```

## Configuration

### Environment Variables

```bash
# TANSS Server Configuration
TANSS_URL=https://your-tanss-server.com
TANSS_TOKEN=your-bearer-token

# Alternative: Username/Password
TANSS_USERNAME=your-username
TANSS_PASSWORD=your-password

# Optional: Advanced Configuration
TANSS_TIMEOUT=30000
TANSS_RETRY_ATTEMPTS=3
TANSS_DEBUG=true
```

### Configuration File

Create `tanss.config.json`:

```json
{
  "url": "https://your-tanss-server.com",
  "auth": {
    "type": "token",
    "token": "your-bearer-token"
  },
  "options": {
    "timeout": 30000,
    "retryAttempts": 3,
    "debug": false
  }
}
```

## AI Agent Examples

### Ticket Management Workflow

```javascript
// AI Agent can automatically handle ticket workflows
async function handleCustomerIssue(customerEmail, issueDescription) {
  // 1. Find customer company
  const companies = await agent.call('tanss.companies.list', {
    search: customerEmail.split('@')[1]
  });
  
  if (companies.length === 0) {
    // 2. Create new company if not found
    const company = await agent.call('tanss.companies.create', {
      name: customerEmail.split('@')[1],
      email: customerEmail
    });
  }
  
  // 3. Create ticket
  const ticket = await agent.call('tanss.tickets.create', {
    title: 'Customer Issue',
    description: issueDescription,
    companyId: companies[0]?.id || company.id,
    priority: 'medium'
  });
  
  return ticket;
}
```

### Automated Reporting

```javascript
// Generate daily ticket report
async function generateDailyReport() {
  const openTickets = await agent.call('tanss.tickets.list', {
    status: 'open'
  });
  
  const urgentTickets = await agent.call('tanss.tickets.list', {
    status: 'open',
    priority: 'urgent'
  });
  
  return {
    totalOpen: openTickets.length,
    urgent: urgentTickets.length,
    tickets: urgentTickets
  };
}
```

### Context-Aware Suggestions

The AI agent can suggest relevant actions based on context:

```javascript
// Agent automatically suggests relevant commands
const suggestions = await agent.suggestActions({
  hasOpenTickets: true,
  ticketManagement: true,
  companyManagement: false
});

// Returns: ['tanss.tickets.list', 'tanss.tickets.create']
```

## Error Handling

The tool provides comprehensive error handling:

```javascript
try {
  const result = await agent.call('tanss.tickets.create', {
    title: 'Test Ticket'
    // Missing required 'description' field
  });
} catch (error) {
  if (error.type === 'validation') {
    console.log('Validation errors:', error.errors);
    // ['Missing required parameter: description']
  } else if (error.type === 'network') {
    console.log('Network error:', error.message);
  } else if (error.type === 'api') {
    console.log('API error:', error.status, error.message);
  }
}
```

## TypeScript Support

Complete TypeScript definitions are included:

```typescript
import { TanssAPI, TicketCreateParams, TicketListParams } from '@layer7/n8n-tanss-api';

interface TicketCreateParams {
  title: string;
  description: string;
  priority?: 'low' | 'medium' | 'high' | 'urgent';
  companyId?: number;
  assigneeId?: number;
  dueDate?: string;
  tags?: string[];
}

interface TicketListParams extends BaseListParams {
  status?: 'open' | 'closed' | 'pending';
  priority?: 'low' | 'medium' | 'high' | 'urgent';
  assigneeId?: number;
  companyId?: number;
  createdAfter?: string;
  createdBefore?: string;
}

// Usage with full type safety
const api = new TanssAPI({
  url: 'https://your-tanss.com',
  token: 'your-token'
});

const tickets: Ticket[] = await api.tickets.list({
  status: 'open',
  limit: 50
});
```

## Versioning & API Coverage

### Endpoint Coverage Matrix

The tool provides 100% coverage of the TANSS API specification:

| Resource | List | Get | Create | Update | Delete | Coverage |
|----------|------|-----|--------|--------|--------|----------|
| Tickets | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Companies | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Employees | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Devices | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Contracts | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Time Entries | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |
| Departments | ✅ | ✅ | ✅ | ✅ | ✅ | 100% |

### Command Schema Export

All commands are exported in `command.schema.json` for AI autocompletion:

```json
{
  "tanss.tickets.list": {
    "name": "tanss.tickets.list",
    "description": "List tickets with filtering and pagination",
    "category": "tickets",
    "resource": "tickets",
    "operation": "list",
    "method": "GET",
    "path": "/tickets",
    "inputSchema": { ... },
    "outputSchema": { ... }
  }
}
```

## Development

### Building from Source

```bash
# Clone repository
git clone https://github.com/julez4125/tanss-n8n-mcp-tool.git
cd tanss-n8n-mcp-tool

# Install dependencies
pnpm install

# Build project
pnpm build

# Run tests
pnpm test

# Start development server
pnpm dev
```

### Adding New Endpoints

The tool automatically discovers new endpoints from the OpenAPI specification:

1. Update the OpenAPI spec file
2. Restart the tool
3. New commands are automatically available

### Custom Resource Modules

```typescript
import { BaseResource } from '@layer7/n8n-tanss-api';

export class CustomResource extends BaseResource {
  async customOperation(params: any) {
    return this.request('GET', '/custom/endpoint', params);
  }
}
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Support

- **Documentation**: [GitHub Wiki](https://github.com/julez4125/tanss-n8n-mcp-tool/wiki)
- **Issues**: [GitHub Issues](https://github.com/julez4125/tanss-n8n-mcp-tool/issues)
- **Discussions**: [GitHub Discussions](https://github.com/julez4125/tanss-n8n-mcp-tool/discussions)

## Changelog

### v1.0.0
- Initial release
- Complete TANSS API integration
- MCP compatibility
- AI agent support
- CLI interface
- n8n GUI integration
- Comprehensive error handling
- Dynamic command discovery
- OpenAPI-based validation

---

**Made with ❤️ for the n8n and AI automation community**
