npm package: @sapmcp/sap-search-mcp
Description: SAP Test Case Search MCP Server - Search and retrieve SAP test cases from Azure AI Search vector database
Author: Saushekh
Latest version: 1.0.3

# SAP Search MCP Server

An npm-based Model Context Protocol (MCP) server for searching SAP test cases from Azure AI Search vector database. This server integrates with Azure AI agents and provides semantic search capabilities for SAP Knowledge House documents.

## Features

- 🔍 **Semantic Search**: Find relevant SAP test cases using natural language
- 📊 **Vector Database Integration**: Leverages Azure AI Search for intelligent search
- 🤖 **Multiple Search Modes**: Single result, multiple options, and selective retrieval
- 🔄 **Automatic Retry Logic**: Handles transient failures gracefully
- 📝 **Rich Formatting**: Returns well-structured results with metadata
- 🏗️ **Production-Ready**: Error handling, logging, and monitoring

## Installation

### Prerequisites

- Node.js 18+ and npm
- Azure AI Search service
- Azure OpenAI service (for embeddings)
- Access to SAP Knowledge House documents (indexed in Azure AI Search)

### From npm Registry

```bash
npm install @saushekh/sap-search-mcp
```

### From GitHub (if published)

```bash
npm install github:saushekh/sap-search-mcp-server
```

### Local Development

```bash
git clone <repository-url>
cd sap-search-mcp-server
npm install
npm run build
npm start
```

## Configuration

### Environment Variables

Create a `.env` file in your project root:

```env
# Azure AI Search
AZURE_SEARCH_ENDPOINT=https://your-search-service.search.windows.net
AZURE_SEARCH_KEY=your_search_key_here
INDEX_KNOWLEDGEHOUSE=knowledgehouse-en
INDEX_QUERYTABLE=querytable

# Azure OpenAI (for embeddings)
AZURE_SEARCH_OPENAI_ENDPOINT=https://your-openai-service.cognitiveservices.azure.com/
AZURE_SEARCH_OPENAI_KEY=your_openai_key_here
EMBEDDING_MODEL=text-embedding-3-large

# Server Configuration
SERVER_PORT=3000
LOG_LEVEL=info
MAX_RETRIES=3
RETRY_DELAY=1000
```

### MCP Server Configuration

In your agent's `mcp.json`:

```json
{
  "servers": {
    "sap-search": {
      "command": "npx",
      "args": [
        "@saushekh/sap-search-mcp"
      ],
      "env": {
        "AZURE_SEARCH_ENDPOINT": "https://your-service.search.windows.net",
        "AZURE_SEARCH_KEY": "your-key",
        "AZURE_SEARCH_OPENAI_ENDPOINT": "https://your-service.cognitiveservices.azure.com/",
        "AZURE_SEARCH_OPENAI_KEY": "your-openai-key"
      },
      "type": "stdio"
    }
  }
}
```

## Usage

### Available Tools

#### 1. `search_sap_test_cases`
Search for a single best-matching SAP test case.

**Parameters:**
- `prompt` (string, required): SAP testing scenario description
  - Example: "Execute Sales & Distribution test case"

**Returns:**
```
Table: [test case table content]
UserGroup: [SAP user group]
QueryName: [query name]
```

#### 2. `search_sap_test_cases_with_options`
Search for multiple SAP test cases with user-configurable results.

**Parameters:**
- `prompt` (string, required): SAP testing scenario description
  - Can include number of results: "Show me 3 Sales test cases"
  - Can use word numbers: "Find top five Financial Accounting test cases"
  - Can use numeric: "Get 2 test cases for MM"
- `k` (integer, optional): Number of results (1-10, default: -1)
  - If -1: extracts from prompt or prompts user

**Returns:**
```
[1] Test Case Header
    🎯 Purpose: Purpose description
    📄 Source: Document Name
    📝 Content: Test case description...

[2] Test Case Header
    ...
```

#### 3. `select_test_case_option`
Select a specific test case from search results.

**Parameters:**
- `option_number` (integer, required): Option number (1-based)
- `original_prompt` (string, required): Original search prompt for context

**Returns:**
```
Table: [selected test case content]
UserGroup: [SAP user group]
QueryName: [query name]
```

## Example Queries

### Single Result Search
```
"Find a test case for creating a sales order"
```

### Multiple Results with Explicit Count
```
"Show me 3 test cases for Material Management"
```

### Multiple Results with Word Number
```
"Find five test cases for Financial Accounting"
```

### Multiple Results with Top Syntax
```
"Get the top 4 test cases for Human Capital Management"
```

## Architecture

### Components

```
┌─────────────────────────────────────────────────────────┐
│           Azure AI Agent / Copilot                       │
└────────────────────┬────────────────────────────────────┘
                     │
                     ▼
        ┌────────────────────────┐
        │  MCP Server (Node.js)   │
        │  - Tool definitions     │
        │  - Request handlers     │
        └────────────┬────────────┘
                     │
        ┌────────────┴─────────────────┐
        │                              │
        ▼                              ▼
┌──────────────────┐        ┌────────────────────┐
│ Azure OpenAI     │        │ Azure AI Search    │
│ (Embeddings)     │        │ (Vector Database)  │
└──────────────────┘        └────────────────────┘
                                      ▲
                                      │
                            ┌─────────┴──────────┐
                            │                    │
                     ┌──────────────┐    ┌──────────────┐
                     │ Knowledge    │    │ Query Table  │
                     │ House Index  │    │ Index        │
                     └──────────────┘    └──────────────┘
```

### Flow

1. **User Query** → Agent receives natural language request
2. **Tool Invocation** → MCP server is called with search parameters
3. **Embedding Generation** → Azure OpenAI generates vector embedding
4. **Vector Search** → Azure AI Search finds matching test cases
5. **Usergroup Lookup** → Secondary search for execution parameters
6. **Result Formatting** → Returns formatted response to agent

## Development

### Project Structure

```
sap-search-mcp-server/
├── src/
│   ├── index.ts                 # Main entry point, server initialization
│   ├── config.ts                # Configuration and environment variables
│   ├── types.ts                 # TypeScript interfaces and types
│   ├── tools/
│   │   ├── searchTestCases.ts   # Single search tool
│   │   ├── searchWithOptions.ts # Multiple search tool
│   │   └── selectTestCase.ts    # Selection tool
│   ├── services/
│   │   ├── azureSearch.ts       # Azure AI Search client
│   │   ├── azureOpenAI.ts       # Azure OpenAI client
│   │   └── searchService.ts     # Core search logic
│   ├── utils/
│   │   ├── logger.ts            # Logging utilities
│   │   ├── retry.ts             # Retry logic with exponential backoff
│   │   └── formatter.ts         # Result formatting
│   └── mcp-handler.ts           # MCP protocol handler
├── dist/                        # Compiled JavaScript
├── package.json
├── tsconfig.json
├── .env.example
└── README.md
```

### Building

```bash
npm run build
```

### Development Mode

```bash
npm run dev
```

### Testing

```bash
npm test
```

## Deployment

### Docker Deployment

```dockerfile
FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY dist ./dist

ENV NODE_ENV=production
ENV LOG_LEVEL=info

EXPOSE 3000

CMD ["node", "dist/index.js"]
```

### Azure Container Instances

```bash
# Build Docker image
docker build -t sap-search-mcp:latest .

# Push to Azure Container Registry
az acr build --registry myregistry --image sap-search-mcp:latest .

# Deploy to ACI
az container create \
  --resource-group mygroup \
  --name sap-search-mcp \
  --image myregistry.azurecr.io/sap-search-mcp:latest \
  --environment-variables \
    AZURE_SEARCH_ENDPOINT=https://... \
    AZURE_SEARCH_KEY=... \
    AZURE_SEARCH_OPENAI_ENDPOINT=https://... \
    AZURE_SEARCH_OPENAI_KEY=...
```

### Cloud Function / Serverless

For Azure Functions, use the HTTP trigger template and adapt the MCP handler.

## Error Handling

The server implements comprehensive error handling:

- **Azure Service Errors**: Logged with context, retried with exponential backoff
- **Configuration Errors**: Clear error messages on startup
- **Input Validation**: Type checking and range validation for parameters
- **Network Errors**: Automatic retry with jitter

## Logging

Logs are written to console with the following levels:

- `error`: Critical issues requiring attention
- `warn`: Warnings about unusual conditions
- `info`: General informational messages (default level)
- `debug`: Detailed debugging information

Set `LOG_LEVEL` environment variable to control verbosity.

## Performance Considerations

- **Embedding Generation**: ~1-2 seconds per search
- **Vector Search**: <100ms for typical queries
- **Usergroup Lookup**: ~1 second (cached when possible)
- **Total Latency**: 2-4 seconds typical

### Optimization Tips

1. **Batch Searches**: For multiple queries, use `search_sap_test_cases_with_options` with k>1
2. **Cache Results**: Store previous search results for repeated queries
3. **Preload Embeddings**: Generate common query embeddings ahead of time

## Troubleshooting

### Connection Errors

```
Error: ECONNREFUSED to Azure AI Search
```

**Solution**: Verify `AZURE_SEARCH_ENDPOINT` and `AZURE_SEARCH_KEY`

### Embedding Failures

```
Error: Embedding generation failed
```

**Solution**: Check `AZURE_SEARCH_OPENAI_ENDPOINT` and `AZURE_SEARCH_OPENAI_KEY`, ensure service has capacity

### No Results Found

```
Error: No relevant table found for the given prompt
```

**Solution**: Rephrase query more specifically, ensure index is populated

### Index Not Found

```
Error: Index 'knowledgehouse-en' not found
```

**Solution**: Run `production_extract_upload.py` to populate Azure AI Search

## Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

MIT © 2024

## Support

For issues and questions:
- 📧 Email: saushekh@example.com
- 🐛 GitHub Issues: [Report a bug](https://github.com/saushekh/sap-search-mcp-server/issues)
- 💬 Discussions: [Ask a question](https://github.com/saushekh/sap-search-mcp-server/discussions)

## Changelog

### v1.0.0 (2024-02-04)
- Initial release
- Support for single and multiple test case searches
- Automatic k extraction from prompts
- Comprehensive error handling and logging
- Azure AI Search and OpenAI integration