# Business Central MCP Agent

A Python agent using **Microsoft Agent Framework** (Semantic Kernel ChatCompletionAgent) to connect directly with Business Central.

## ✨ Features

- **Direct Connection** - No exe file needed! Connects directly to Business Central MCP HTTP endpoint
- **Cross-Platform** - Works on Windows, macOS, and Linux
- **Flexible Authentication** - Supports both device code flow (delegated) and client credentials (application)
- **Microsoft Agent Framework** - Uses Semantic Kernel ChatCompletionAgent pattern

## Quick Start

1. **Install dependencies**:
```bash
pip install -r requirements.txt
```

2. **Configure** `BusinessCentralMCP.env`:
```env
# Azure OpenAI
AZURE_OPENAI_API_KEY=your_key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-4o

# Business Central
BC_TENANT_ID=your_tenant_id
BC_CLIENT_ID=your_client_id
# BC_CLIENT_SECRET=your_secret  # Optional - for service principal auth
BC_ENVIRONMENT_NAME=Production
BC_COMPANY_NAME=CRONUS International Ltd.
```

3. **Run**:
```bash
python bc_direct_agent.py
```

**Authentication Options:**

- **Device Code Flow (default)**: Interactive browser authentication - agent prompts you to visit a URL and enter a code
- **Client Credentials Flow**: Add `BC_CLIENT_SECRET` to use service principal authentication (no user interaction)

## Architecture

This implementation follows the Microsoft Agent Framework pattern:

```
User Question
    ↓
ChatCompletionAgent (Semantic Kernel)
    ↓
BusinessCentralMCPPlugin (@kernel_function decorators)
    ↓
MCP Client Session (stdio_client)
    ↓
BcMCPProxy.exe (MCP Server)
    ↓
Business Central API
```

### Key Components

1. **Semantic Kernel Kernel** - Core framework
2. **ChatCompletionAgent** - The agent from `semantic_kernel.agents`
3. **BusinessCentralMCPPlugin** - Plugin with `@kernel_function` decorators
4. **FunctionChoiceBehavior.Auto()** - Enables automatic function calling
5. **MCP ClientSession** - Connects to BC MCP Server via stdio

## Prerequisites

1. **Business Central MCP Server (BcMCPProxy.exe)**
   - Download/build from: https://github.com/microsoft/BCTech/tree/master/samples/BcMCPProxy
   - Place `BcMCPProxy.exe` in this directory or update path in `.env`

2. **Azure AD App Registration**
   - Create app registration in Azure Portal
   - Add redirect URL: `ms-appx-web://Microsoft.AAD.BrokerPlugin/<clientID>`
   - Add API permissions:
     - `Financials.ReadWrite.All` (Delegated)
     - `user_impersonation` (Delegated)

3. **Python 3.10+**

4. **Azure OpenAI or OpenAI API Key**

## Installation

1. Clone this repository:
```bash
git clone <repository-url>
cd BusinessCentralMCPserver
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Configure environment variables:
   - Edit `BusinessCentralMCP.env` and fill in your values:
     - Azure OpenAI credentials
     - BC MCP Server path
     - Azure tenant/client IDs
     - BC environment and company name

## Configuration

Edit `BusinessCentralMCP.env`:

```env
# Azure OpenAI
AZURE_OPENAI_API_KEY=your_key_here
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=your_deployment
AZURE_OPENAI_API_VERSION=2024-08-01-preview

# Business Central MCP Server
BC_MCP_SERVER_PATH=BcMCPProxy.exe
BC_TENANT_ID=your_tenant_id
BC_CLIENT_ID=your_client_id
BC_ENVIRONMENT_NAME=production
BC_COMPANY_NAME=CRONUS International Ltd.
BC_CONFIG_NAME=default
```

## Usage

Run the agent:

```bash
python bc_mcp_agent.py
```

The agent will:
1. Initialize Semantic Kernel
2. Connect to BC MCP Server
3. Discover available BC tools
4. Start an interactive chat session

### Example Interactions

```
> What tools are available?
[Agent lists all BC MCP tools]

> Show me customer information
[Agent calls appropriate BC tool and displays results]

> List recent sales orders
[Agent queries BC and formats the response]
```

## How It Works

### Microsoft Agent Framework Pattern

This implementation uses the **exact pattern** from the Semantic-Kernel-PlantRequestAgent reference:

1. **Kernel Setup**
   ```python
   kernel = Kernel()
   add_chat_service(kernel)  # Azure OpenAI or OpenAI
   ```

2. **Plugin Creation**
   ```python
   class BusinessCentralMCPPlugin:
       @kernel_function(description="...", name="...")
       async def call_bc_tool(self, tool_name: str, arguments: str) -> str:
           # Calls MCP server
   ```

3. **Plugin Registration**
   ```python
   kernel.add_plugin(bc_plugin, plugin_name="business_central")
   ```

4. **Agent Creation**
   ```python
   agent = ChatCompletionAgent(
       name="BusinessCentralAgent",
       instructions=system_prompt,
       kernel=kernel,
       function_choice_behavior=FunctionChoiceBehavior.Auto()
   )
   ```

5. **Interactive Loop**
   ```python
   async for response_item in agent.invoke(user_input):
       print(response_item.content, end="")
   ```

### MCP Connection

The agent connects to BcMCPProxy.exe using stdio (standard input/output):

```python
async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        await session.initialize()
        # Use session to call tools
```

## Differences from PlantRequestAgent

The PlantRequestAgent makes **direct HTTP API calls** to Business Central:
```python
async with httpx.AsyncClient() as client:
    response = await client.get(url, headers=headers)
```

This BC MCP Agent connects through the **MCP Server** instead:
```python
result = await session.call_tool(tool_name, arguments=args_dict)
```

Benefits of MCP approach:
- Abstracted authentication (handled by MCP server)
- Simplified API access
- Compatible with other MCP clients (Claude Desktop, VS Code)
- Centralized BC access logic

## Troubleshooting

### MCP Server Not Found
```
❌ Error: BC MCP Server not found at: BcMCPProxy.exe
```
**Solution**: Update `BC_MCP_SERVER_PATH` in `.env` with full path to BcMCPProxy.exe

### Authentication Errors
```
❌ Error connecting to BC MCP Server: ...
```
**Solution**: 
1. Check Azure AD app registration
2. Verify redirect URL format
3. Ensure API permissions are granted
4. Confirm tenant/client IDs are correct

### Connection Timeout
**Solution**:
1. Verify BC environment name is correct
2. Check company name (case-sensitive)
3. Test network connectivity to BC

## References

- **BcMCPProxy**: https://github.com/microsoft/BCTech/tree/master/samples/BcMCPProxy
- **MCP Protocol**: https://modelcontextprotocol.io/
- **Semantic Kernel**: https://learn.microsoft.com/en-us/semantic-kernel/
- **Microsoft Agent Framework**: Combination of Semantic Kernel ChatCompletionAgent

## License

MIT License
