# IBM i MCP Server

A Model Context Protocol (MCP) server that enables AI assistants to interact with IBM i AS/400 source members, providing seamless integration for source code management, compilation, and development workflows.

## 🚀 Features

- **🔗 IBM i Integration**: Connect to IBM i AS/400 systems
- **📂 Source Member Management**: Read, write, list, and manage source members
- **🔧 Compilation Support**: Compile RPG, DDS, and other source types  
- **🏷️ Automatic Source Marking**: Apply source mark "5719A" to all modifications
- **🌐 MCP Protocol**: Full Model Context Protocol compliance
- **🎯 AI Assistant Ready**: Direct integration with ChatGPT, Claude, and other AI tools

## 📋 Table of Contents

- [Quick Start](#quick-start)
- [Installation](#installation)
- [Configuration](#configuration)
- [Tools Reference](#tools-reference)
- [Resources](#resources)
- [Examples](#examples)
- [Development](#development)
- [Contributing](#contributing)

## ⚡ Quick Start

### 1. Install Dependencies

```bash
git clone https://github.com/[your-username]/ibmi-mcp-server.git
cd ibmi-mcp-server
npm install
```

### 2. Build the Server

```bash
npm run build
```

### 3. Test Installation

```bash
npm test
```

### 4. Configure MCP Client

Add to your MCP client configuration:

```json
{
  "mcpServers": {
    "ibmi-mcp-server": {
      "command": "node",
      "args": ["path/to/ibmi-mcp-server/build/index.js"]
    }
  }
}
```

### 5. Start Using

Connect to your IBM i system and start managing source members through your AI assistant!

## 🛠 Installation

### Prerequisites

- **Node.js** 18.0.0 or higher
- **npm** (comes with Node.js)
- Access to IBM i AS/400 system
- MCP-compatible AI assistant or client

### Local Development Setup

```bash
# Clone the repository
git clone https://github.com/[your-username]/ibmi-mcp-server.git
cd ibmi-mcp-server

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Start development mode (with auto-reload)
npm run dev
```

### Production Deployment

```bash
# Install production dependencies only
npm ci --production

# Build for production
npm run build

# Start the server
npm start
```

## ⚙️ Configuration

### Environment Variables

Create a `.env` file in the project root:

```env
# Default IBM i connection settings
DEFAULT_IBMI_HOST=your-ibmi-system.com
DEFAULT_IBMI_USER=your-username
DEFAULT_LIBRARY=QGPL
DEFAULT_SOURCE_FILE=QRPGLESRC

# Development settings
NODE_ENV=development
DEBUG=false
```

### MCP Client Integration

#### For VS Code with MCP Extension

Add to your VS Code settings or MCP configuration file:

```json
{
  "mcpServers": {
    "ibmi-mcp-server": {
      "command": "node",
      "args": ["C:\\path\\to\\ibmi-mcp-server\\build\\index.js"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}
```

#### For Claude Desktop

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "ibmi": {
      "command": "node",
      "args": ["path/to/ibmi-mcp-server/build/index.js"]
    }
  }
}
```

## 🔧 Tools Reference

### `connect_ibmi`
Connect to an IBM i AS/400 system.

**Parameters:**
- `host` (string, required): IBM i system hostname or IP
- `user` (string, required): User profile name
- `password` (string, optional): Password
- `port` (number, default: 23): Connection port
- `library` (string, default: "QGPL"): Default library
- `sourceFile` (string, default: "QRPGLESRC"): Default source file

**Example:**
```json
{
  "host": "ibmi-system.company.com",
  "user": "DEVELOPER",
  "library": "MYLIB",
  "sourceFile": "QRPGLESRC"
}
```

### `list_source_members`
List source members with optional filtering.

**Parameters:**
- `library` (string, optional): Library name
- `sourceFile` (string, optional): Source physical file name
- `member` (string, optional): Member name pattern
- `type` (string, optional): Source type filter (RPGLE, DSPF, etc.)

**Example:**
```json
{
  "library": "MYLIB",
  "sourceFile": "QRPGLESRC", 
  "type": "RPGLE"
}
```

### `read_source_member`
Read source member content with optional line range.

**Parameters:**
- `member` (string, required): Source member name
- `library` (string, optional): Library name
- `sourceFile` (string, optional): Source file name
- `startLine` (number, optional): Starting line number
- `endLine` (number, optional): Ending line number

**Example:**
```json
{
  "member": "MYPROG",
  "startLine": 1,
  "endLine": 100
}
```

### `write_source_member`
Write or update source member with automatic "5719A" source marking.

**Parameters:**
- `member` (string, required): Source member name
- `content` (string, required): Source member content
- `library` (string, optional): Library name
- `sourceFile` (string, optional): Source file name
- `sourceType` (string, optional): Source type (RPGLE, DSPF, etc.)
- `description` (string, optional): Member description

**Example:**
```json
{
  "member": "MYPROG",
  "content": "// RPG code here...",
  "sourceType": "RPGLE",
  "description": "Updated by AI assistant"
}
```

### `compile_source_member`
Compile a source member.

**Parameters:**
- `member` (string, required): Source member name
- `library` (string, optional): Library name
- `sourceFile` (string, optional): Source file name
- `sourceType` (string, optional): Source type
- `options` (string, optional): Compile options

**Example:**
```json
{
  "member": "MYPROG",
  "sourceType": "RPGLE",
  "options": "OPTION(*EVENTF)"
}
```

## 📚 Resources

### Source Member Resource

Access IBM i source members as MCP resources using URI templates:

**URI Pattern:** `ibmi://source/{library}/{sourceFile}/{member}`

**Examples:**
- `ibmi://source/MYLIB/QRPGLESRC/MYPROG`
- `ibmi://source/TESTLIB/QDDSSRC/MYDSPF`
- `ibmi://source/PRODLIB/QCPYSRC/MYCPY`

## 💡 Examples

### Example 1: Connect and List Members

```javascript
// Connect to IBM i
await callTool("connect_ibmi", {
  host: "ibmi-system.company.com",
  user: "DEVELOPER",
  library: "MYLIB"
});

// List RPG source members
const members = await callTool("list_source_members", {
  type: "RPGLE"
});
```

### Example 2: Read and Modify Source

```javascript
// Read existing source member
const source = await callTool("read_source_member", {
  member: "MYPROG"
});

// Modify the source (add your changes)
const updatedSource = source.content + "\n// Added by AI assistant";

// Write back with automatic source marking
await callTool("write_source_member", {
  member: "MYPROG", 
  content: updatedSource,
  sourceType: "RPGLE",
  description: "Enhanced by AI"
});
```

### Example 3: Compile and Check Results

```javascript
// Compile the source member
const compileResult = await callTool("compile_source_member", {
  member: "MYPROG",
  sourceType: "RPGLE"
});

console.log("Compilation:", compileResult.success ? "SUCCESS" : "FAILED");
```

### Example 4: Using Resources

```javascript
// Access source member as a resource
const resource = await readResource("ibmi://source/MYLIB/QRPGLESRC/MYPROG");
console.log("Source content:", resource.contents[0].text);
```

## 🏗 Development

### Development Scripts

```bash
# Start development mode with auto-reload
npm run dev

# Build the project
npm run build

# Run the server
npm start

# Run tests
npm test

# Lint code
npm run lint

# Open MCP Inspector (if installed)
npm run inspector
```

### Adding New Tools

1. **Define the tool in `src/index.ts`:**

```typescript
server.registerTool(
  "my_new_tool",
  {
    description: "Description of what the tool does",
    inputSchema: {
      parameter1: z.string().describe("Parameter description"),
      parameter2: z.number().optional().describe("Optional parameter"),
    },
  },
  async ({ parameter1, parameter2 }) => {
    // Tool implementation
    return {
      content: [
        {
          type: "text",
          text: `Result: ${parameter1}`,
        },
      ],
    };
  }
);
```

2. **Build and test:**

```bash
npm run build
npm test
```

### VS Code Development

The project includes VS Code configuration for debugging:

1. **Open project in VS Code**
2. **Set breakpoints in source code**
3. **Press F5 to start debugging**
4. **Use the Debug Console to interact with the server**

## 🔒 Security Considerations

- **Never commit credentials** to version control
- **Use environment variables** for sensitive configuration
- **Implement proper IBM i user permissions**
- **Validate all input parameters**
- **Use secure connection methods** for IBM i access

## 📄 Source Marking

All source modifications automatically receive the **"5719A"** source mark:

- **RPG Sources**: Mark applied at position 75+
- **DDS Sources**: Mark applied at position 81+
- **Other Sources**: Mark applied at appropriate position based on source type

This ensures compliance with source marking standards and tracks AI-assisted modifications.

## 🐛 Troubleshooting

### Common Issues

**Build fails with module errors:**
```bash
npm install
npm run build
```

**Server won't connect to IBM i:**
- Check host/port settings
- Verify user credentials
- Ensure network connectivity

**Source marking issues:**
- Source mark "5719A" is applied automatically
- Check line length limits for your source type

**MCP client connection issues:**
- Verify the correct path to build/index.js
- Check Node.js version (18.0.0+ required)
- Ensure the server builds successfully

### Debug Mode

Run with verbose logging:

```bash
DEBUG=* npm start
```

### Getting Help

- **📖 Documentation**: See [DEVELOPMENT_GUIDE.md](./DEVELOPMENT_GUIDE.md)
- **🐛 Issues**: [GitHub Issues](https://github.com/[your-username]/ibmi-mcp-server/issues)
- **💬 Discussions**: [GitHub Discussions](https://github.com/[your-username]/ibmi-mcp-server/discussions)

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.

### Quick Contribution Steps

1. **Fork the repository**
2. **Create a feature branch:** `git checkout -b feature/amazing-feature`
3. **Make your changes**
4. **Add tests if applicable**
5. **Run quality checks:** `npm run lint && npm test`
6. **Commit changes:** `git commit -m "Add amazing feature"`
7. **Push to branch:** `git push origin feature/amazing-feature`
8. **Open a Pull Request**

## 📜 License

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

## 🙏 Acknowledgments

- **Model Context Protocol** team for the excellent SDK
- **IBM i community** for inspiration and requirements
- **VS Code** and **TypeScript** teams for amazing developer tools

## 🌟 Star History

If this project helps you, please consider giving it a star! ⭐

---

**Built with ❤️ for the IBM i community**

*Enable your AI assistants to work directly with IBM i AS/400 source members while maintaining professional source marking standards.*
