Skip to main content
Glama
README.md
# WebMCP

A dual-mode server (HTTP + MCP) that exposes a sample e-commerce website functionality as tools that AI agents can discover and invoke programmatically — without navigating pages or parsing HTML.

---

## Table of Contents

1. [Background](#background)
2. [Architecture Overview](#architecture-overview)
3. [Project Structure](#project-structure)
4. [MCP Tools](#mcp-tools)
5. [How Requests Flow](#how-requests-flow)
6. [Authentication](#authentication)
7. [Service Layer](#service-layer)
8. [Configuration](#configuration)
9. [Running Locally](#running-locally)
10. [Deployment](#deployment)
11. [Current Status and Open Items](#current-status-and-open-items)
12. [Page-Scoped Tools](#page-scoped-tools)

---

## Background

### What problem does this solve?

Online shops are built for human visitors. AI agents (like Claude, GPT, etc.) that need to interact with a shop currently have no structured way to search products, browse categories, or discover promotions. They would have to navigate web pages and parse raw HTML, which is fragile, slow, and error-prone.

### What does this project do?

This project provides a **server** that wraps an e-commerce website's core functionality into clean, well-defined **tools** that AI agents can call. It speaks two protocols:

- **HTTP** — a simple REST-like JSON API for direct tool invocation
- **MCP (Model Context Protocol)** — an open protocol that allows AI agents (Claude Desktop, MCP-compatible clients, etc.) to automatically discover and use the available tools

---

## Architecture Overview

```
                                ┌─────────────────────────────┐
                                │      Google Cloud Run        │
                                │                              │
  AI Agent ──── MCP Protocol ──▶│  /mcp   → MCP Server        │
                                │            │                 │
  HTTP Client ── POST JSON ───▶│  /     → HTTP Handler        │
                                │            │                 │
                                │     ┌──────┴──────┐         │
                                │     │  Tool Layer  │         │
                                │     │  (5 tools)   │         │
                                │     └──────┬──────┘         │
                                │     ┌──────┴──────┐         │
                                │     │Service Layer │         │
                                │     │ (data access)│         │
                                │     └─────────────┘         │
                                └─────────────────────────────┘
```

The architecture has three layers:

1. **Entry Point & Routing** ([src/index.ts](src/index.ts)) — A single Google Cloud Function (`webMcp`) that handles all incoming HTTP requests. It authenticates the caller, then routes to either the MCP transport handler or the direct HTTP tool handler based on the URL path.

2. **Tool Layer** ([src/mcp/](src/mcp/)) — Defines five tools with input validation (Zod schemas), descriptions for AI agents, and handler functions. Each tool calls into the service layer and formats results as text content.

3. **Service Layer** ([src/services/](src/services/)) — Data access functions that fetch product, category, banner, and navigation data. This layer includes an in-memory TTL cache for expensive operations. **Currently stubbed** — see [Current Status](#current-status-and-open-items).

### Why dual-mode?

- **MCP mode** (`/mcp`) lets MCP-compatible AI agents (Claude Desktop, etc.) auto-discover all available tools via the standard `tools/list` protocol method and call them via `tools/call`. No integration code needed on the agent side.
- **HTTP mode** (`POST /`) lets non-MCP clients (internal admin UIs, scripts, other services) call the same tools via a simple JSON API, following the team's established response envelope format.

Both modes share the same tool implementations and service layer — there is no code duplication.

---

## Project Structure

```
WebMCP/
│
├── src/
│   ├── index.ts                        # Entry point — exports the Cloud Function, routes requests
│   │
│   ├── auth/
│   │   └── validateToken.ts            # X-Winp-Token authentication against admin API
│   │
│   ├── config/
│   │   └── index.ts                    # Environment variable configuration
│   │
│   ├── types/
│   │   └── index.ts                    # Shared TypeScript interfaces (Product, Category, Banner, etc.)
│   │
│   ├── utils/
│   │   ├── errors.ts                   # Error classes: AppError, ValidationError, NotFoundError
│   │   └── response.ts                 # Standard JSON response envelope builders
│   │
│   ├── services/
│   │   ├── cache.ts                    # Generic in-memory TTL cache (used by categories + banners)
│   │   ├── search.ts                   # Product search data access (STUB)
│   │   ├── categories.ts              # Category tree + category browsing data access (STUB)
│   │   ├── banners.ts                 # Promoted banners data access (STUB)
│   │   └── navigation.ts             # Hardcoded site navigation links
│   │
│   └── mcp/
│       ├── server.ts                   # Creates McpServer instance and registers all tools
│       └── tools/
│           ├── types.ts                # ToolDefinition and ToolResult interfaces
│           ├── index.ts                # Tool registry — exports allTools array
│           ├── product-search.ts       # search_products tool definition
│           ├── category-browse.ts      # list_categories + browse_category tool definitions
│           ├── banners.ts              # get_promoted_banners tool definition
│           └── navigation.ts           # get_navigation_links tool definition
│
├── deploy/
│   ├── test.env.yaml                   # Environment variables for test deployment
│   └── prod.env.yaml                   # Environment variables for production deployment
│
├── package.json                        # Node.js project manifest and scripts
├── tsconfig.json                       # TypeScript compiler configuration
├── Dockerfile                          # Multi-stage Docker build for Cloud Run
├── deploy.sh                           # Generic Cloud Run deployment script
├── .env.sample                         # Template for local environment variables
├── .env.deploy.sample                  # Template for deployment configuration
├── .gitignore
└── .dockerignore
```

### File-by-file explanation

#### `src/index.ts` — Entry Point

This is the only exported Cloud Function (`webMcp`). It handles all incoming HTTP traffic:

1. **CORS preflight** — Responds to `OPTIONS` requests with allowed methods/headers.
2. **Authentication** — Extracts the `X-Winp-Token` header, validates it against the admin API. Rejects with 401 if missing or invalid.
3. **Routing**:
   - `GET/POST /mcp` → Creates a stateless MCP server and transport, delegates the request to the MCP Streamable HTTP handler. This is the route AI agents connect to.
   - `POST /` → Parses the JSON payload to extract a tool name and parameters, finds the matching tool, executes it, and returns the result in the standard response envelope.
   - Anything else → 404.

#### `src/auth/validateToken.ts` — Authentication

Validates the `X-Winp-Token` by calling the admin API:

```
GET {ADMIN_BASE_URL}/winp/token/admin/{MODULE_PATH}/{MODULE_SCOPE}/{token}
```

On success, the admin API returns `{ email, account, driveId }`. The function returns an `AuthValidationResult` with either `{ success: true, data: { email, account, driveId } }` or `{ success: false, error: "..." }`.

#### `src/config/index.ts` — Configuration

Reads environment variables with sensible defaults:

| Variable | Default | Purpose |
|---|---|---|
| `PORT` | `3000` | HTTP server port |
| `ADMIN_BASE_URL` | Test admin API URL | Base URL of the admin API used for token validation |
| `MODULE_PATH` | `web-mcp` | Token validation module path |
| `MODULE_SCOPE` | `web-mcp` | Token validation module scope |
| `SHOP_BASE_URL` | `https://www.example-shop.com` | Base URL of the target shop |
| `CACHE_TTL_CATEGORIES_MS` | `3600000` (1 hour) | How long to cache the category tree |
| `CACHE_TTL_BANNERS_MS` | `900000` (15 min) | How long to cache banner data |

#### `src/types/index.ts` — Shared Types

Defines the core data structures used across the project:

- **`AuthData`** / **`AuthValidationResult`** — Authentication types
- **`ApiResponse<T>`** — Standard JSON response envelope (`{ success, status, code, payload, tm, errors }`)
- **`Product`** — `{ title, price, imageUrl, productUrl, sku }`
- **`Category`** — `{ id, name, url, children: Category[] }` (recursive tree)
- **`Banner`** — `{ title, imageUrl, link, filterQuery }`
- **`NavigationLink`** — `{ name, url, type }` where type is one of `customer_service | shopping | account | info | language`

#### `src/utils/response.ts` — Response Envelope

Two helper functions that construct the standard response envelope:

- `successResponse(payload)` → `{ success: true, status: "SUCCESS", code: 200, payload, tm: "...", errors: [] }`
- `errorResponse(code, errors)` → `{ success: false, status: "ERROR", code, payload: [], tm: "...", errors }`

#### `src/utils/errors.ts` — Error Classes

- `AppError(statusCode, message, code, details?)` — Base error with HTTP status
- `ValidationError(message)` — 400 error
- `NotFoundError(message)` — 404 error

#### `src/services/cache.ts` — TTL Cache

A generic in-memory cache with time-to-live expiration. Used by the category and banner services to avoid refetching data on every request.

```typescript
const cache = new TtlCache<string[]>(60_000); // 1 minute TTL
cache.set("key", ["a", "b"]);
cache.get("key"); // ["a", "b"] — or undefined if expired
```

#### `src/services/navigation.ts` — Navigation Links

The only fully implemented service. Returns a hardcoded list of the actionable links on the target shop, each prefixed with `SHOP_BASE_URL`:

- Customer service
- My account and login
- Shopping basket
- Informational pages (e.g. jobs)
- Language switcher (one link per supported language)

Paths differ from shop to shop, so they are defined in `navigation.ts`. These are structural links that rarely change, so hardcoding is appropriate.

#### `src/services/search.ts`, `categories.ts`, `banners.ts` — Data Access (STUBS)

These three services define the function signatures and interfaces but currently return empty results. They are placeholders awaiting a decision on the data access strategy (see [Open Items](#current-status-and-open-items)).

- `searchProducts({ query, limit?, language? })` → `Product[]`
- `listCategories(language?)` → `Category[]` (with TTL caching)
- `browseCategory({ categoryId, page?, limit?, sort?, language? })` → `Product[]`
- `getPromotedBanners(language?)` → `Banner[]` (with TTL caching)

#### `src/mcp/server.ts` — MCP Server Factory

Creates a new `McpServer` instance (from `@modelcontextprotocol/sdk`) and registers all five tools from the tool registry. Each tool is wrapped with error handling — if a tool handler throws, the error is caught and returned as an MCP error result rather than crashing the server.

#### `src/mcp/tools/*.ts` — Tool Definitions

Each tool file exports a `ToolDefinition` object with:
- `name` — unique tool identifier
- `description` — human-readable text that helps AI agents understand when/how to use the tool
- `inputSchema` — a Zod schema that validates and documents the tool's input parameters
- `handler` — async function that calls the service layer and returns an MCP-compatible result

See the [MCP Tools](#mcp-tools) section below for details on each tool.

---

## MCP Tools

### 1. `search_products`

**Purpose:** Search for products by keyword.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `query` | string | Yes | Search query (e.g. "schuhe", "gartenmöbel") |
| `limit` | number (1-50) | No | Max results to return. Default: 10 |
| `language` | "de" \| "fr" | No | Language for results. Default: "de" |

**Returns:** Array of `{ title, price, imageUrl, productUrl, sku }`

### 2. `list_categories`

**Purpose:** Get the full category hierarchy of the website.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `language` | "de" \| "fr" | No | Language for category names. Default: "de" |

**Returns:** Recursive tree of `{ id, name, url, children: [...] }`

### 3. `browse_category`

**Purpose:** Browse products within a specific category.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `category_id` | string | Yes | Category ID (from `list_categories`) |
| `page` | number (min 1) | No | Page number. Default: 1 |
| `limit` | number (1-50) | No | Products per page. Default: 10 |
| `sort` | string | No | Sort order (e.g. "price_asc", "price_desc") |
| `language` | "de" \| "fr" | No | Language. Default: "de" |

**Returns:** Array of `{ title, price, imageUrl, productUrl, sku }`

### 4. `get_promoted_banners`

**Purpose:** Get current homepage promotional banners.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `language` | "de" \| "fr" | No | Language. Default: "de" |

**Returns:** Array of `{ title, imageUrl, link, filterQuery }`

### 5. `get_navigation_links`

**Purpose:** Get all actionable navigation links on the site.

| Parameter | Type | Required | Description |
|---|---|---|---|
| *(none)* | — | — | — |

**Returns:** Array of `{ name, url, type }` covering customer service, account, basket, language switcher, jobs, etc.

---

## How Requests Flow

### MCP Protocol Flow (AI Agent → `/mcp`)

```
1. AI Agent sends HTTP POST to /mcp with JSON-RPC body
2. index.ts validates X-Winp-Token header
3. index.ts creates a new McpServer + StreamableHTTPServerTransport
4. Transport handles the JSON-RPC message:
   - "tools/list" → returns all 5 tool definitions with schemas
   - "tools/call" → finds the tool, validates input via Zod, calls handler
5. Tool handler calls the service layer (e.g. searchProducts())
6. Result is returned as MCP content (JSON text)
7. Server and transport are closed (stateless)
```

### HTTP Flow (Client → `POST /`)

```
1. Client sends POST to / with body:
   { "payload": [{ "tool": "search_products", "params": { "query": "schuhe" } }] }
2. index.ts validates X-Winp-Token header
3. index.ts extracts tool name and params from payload
4. Finds the matching tool in the registry
5. Calls the tool handler with params
6. Wraps result in standard response envelope:
   { "success": true, "status": "SUCCESS", "code": 200,
     "payload": [{ "tool": "search_products", "result": [...] }],
     "tm": "2026-04-17T...", "errors": [] }
```

---

## Authentication

All requests (both MCP and HTTP) require the `X-Winp-Token` header. The token is validated by calling the admin API:

```
GET {ADMIN_BASE_URL}/winp/token/admin/{MODULE_PATH}/{MODULE_SCOPE}/{token}
```

- **200 response** with `{ email, account, driveId }` → token is valid
- **Any other response** → token is rejected with HTTP 401

---

## Service Layer

The service layer is the bridge between tool definitions and actual data. It is designed with a clean separation so that the data access strategy can be swapped without changing the tool layer.

### Implemented

- **`navigation.ts`** — Fully implemented. Returns hardcoded navigation links derived from the live site structure.

### Stubbed (awaiting data access research)

- **`search.ts`** — Returns empty `Product[]`. Needs to be connected to a product search API.
- **`categories.ts`** — Returns empty `Category[]`. Needs to fetch the category tree and enable category-based product browsing.
- **`banners.ts`** — Returns empty `Banner[]`. Needs to fetch current homepage promotional banners.

### Caching

The category and banner services use `TtlCache` to avoid refetching on every request:
- Category tree: cached for **1 hour** (configurable via `CACHE_TTL_CATEGORIES_MS`)
- Banners: cached for **15 minutes** (configurable via `CACHE_TTL_BANNERS_MS`)

---

## Configuration

### Local Development

Copy `.env.sample` to `.env` and fill in values:

```env
# Local development: skip token auth (never enable in production)
SKIP_AUTH=false

# Cache TTLs (milliseconds)
CACHE_TTL_CATEGORIES_MS=3600000
CACHE_TTL_BANNERS_MS=900000
```

Any variable not set in `.env` (such as `SHOP_BASE_URL` or `ADMIN_BASE_URL`) falls back to the default in `src/config/index.ts`. Add it to `.env` to override it.

### Deployment

Copy `.env.deploy.sample` to `.env.deploy` and fill in GCP-specific values:

```env
GCP_PROJECT=your-gcp-project-id
REGION=europe-west6
AR_REPOSITORY=web-mcp
IMAGE_NAME=admin-fn-web-mcp
SA_EMAIL=your-service-account@your-project.iam.gserviceaccount.com
FUNCTIONS="webMcp:web-mcp"
```

Environment-specific runtime config is in `deploy/test.env.yaml` and `deploy/prod.env.yaml`.

---

## Running Locally

### Prerequisites

- Node.js 24+
- npm

### Setup

```bash
npm install
cp .env.sample .env   # then edit .env with your values
```

### Build

```bash
npm run build        # compiles TypeScript → dist/
npm test             # type-check only (no unit tests yet)
```

### Start

```bash
npm start            # starts the Cloud Functions Framework on port 8080
```

### Test HTTP endpoint

```bash
curl -X POST http://localhost:8080/ \
  -H "Content-Type: application/json" \
  -H "X-Winp-Token: YOUR_TOKEN" \
  -d '{"payload": [{"tool": "get_navigation_links", "params": {}}]}'
```

### Test MCP endpoint

Use an MCP client (e.g. Claude Desktop, MCP Inspector) pointed at `http://localhost:8080/mcp` with the `X-Winp-Token` header.

---

## Deployment

The project deploys to **Google Cloud Run**.

### Docker Build

The `Dockerfile` uses a multi-stage build:
1. **Builder stage** — installs all dependencies, compiles TypeScript
2. **Runner stage** — installs production dependencies only, copies compiled JS, runs via `functions-framework`

### Deploy Command

```bash
cp .env.deploy.sample .env.deploy   # fill in GCP values
./deploy.sh test                     # deploy to test environment
./deploy.sh prod                     # deploy to production
```

The deploy script:
1. Ensures the Artifact Registry repository exists
2. Builds and pushes the Docker image (tagged with env + git short SHA)
3. Deploys to Cloud Run with the environment variables from `deploy/<env>.env.yaml`

---

## Current Status and Open Items

### What is complete

| Component | Status | Notes |
|---|---|---|
| Project scaffolding | Done | package.json, tsconfig, Docker, deploy pipeline |
| Authentication | Done | X-Winp-Token validation against the admin API |
| Response envelope | Done | Standard `{ success, status, code, payload, tm, errors }` format |
| Error handling | Done | AppError, ValidationError, NotFoundError |
| MCP server | Done | McpServer with Streamable HTTP transport |
| HTTP routing | Done | Dual-mode: `/mcp` for MCP, `POST /` for direct HTTP |
| Tool definitions (all 5) | Done | Schemas, descriptions, handlers — all wired up |
| Navigation service | Done | Hardcoded links for all actionable site pages |
| TTL cache | Done | Generic cache used by categories and banners |
| Service stubs | Done | search, categories, banners — interfaces defined, return empty |
| Deployment config | Done | Dockerfile, deploy.sh, test + prod env files |

### What is NOT complete

| Item | Blocker | Description |
|---|---|---|
| **Service layer → Narrative API** | API integration | `search.ts`, `categories.ts`, and `banners.ts` are stubs returning empty results. Data source is confirmed as the **Narrative API** — stubs need to be wired to actual API calls. |
| **Page-scoped tool filtering** | Implementation | Different pages should expose different MCP tools based on allowed operations. Design is documented; code not yet implemented. |

### Data Access Strategy: Narrative API

There is **no need to scrape the shop's website**. The product, category, and banner data is already indexed on the search platform, and the service layer will use its **Narrative API** as the sole data source.

The purpose of this MCP server is to build tools that tell AI **how to discover, access, and use** that existing data to answer user questions. Examples:

- User asks *"I wonder if this shop has ongoing promos?"* → AI calls `get_promoted_banners` → gets banner data from Narrative API
- User asks *"I wonder if this shop has a category for shoes?"* → AI calls `list_categories` → gets category tree from Narrative API
- User asks *"I wonder if this shop has this specific product in stock?"* → AI calls `search_products` → queries Narrative API

### Remaining Implementation Tasks

1. **Wire service stubs to Narrative API** — Replace the empty returns in `search.ts`, `categories.ts`, and `banners.ts` with actual Narrative API calls
2. **Page-scoped tool filtering** — See [Page-Scoped Tools](#page-scoped-tools) below

---

## Page-Scoped Tools

Different pages on a shop's website support different operations. For example, the homepage has banners and promotions, the category page supports browsing, and the search results page supports product search. Rather than exposing all tools on every page, the MCP server filters the available tools based on which page the user is currently on.

### How it works

The client sends a `page` identifier (via the `X-Page-Context` header for HTTP, or as a parameter in MCP requests) that tells the server which page the user is viewing. The server then returns only the tools that are relevant to that page context.

### Page → Tool mapping

| Page Context | Available Tools | Rationale |
|---|---|---|
| `home` | `get_promoted_banners`, `get_navigation_links`, `search_products` | Homepage shows promos, navigation, and has a search bar |
| `category` | `list_categories`, `browse_category`, `search_products` | Category pages support browsing and searching |
| `search` | `search_products`, `list_categories` | Search results page; categories help refine |
| `product` | `search_products` | Product detail page; search for alternatives |
| `*` (default) | All tools | Fallback when no page context is provided |

### Why?

This design:
- **Reduces noise** — AI agents only see tools relevant to the current context, making them more likely to pick the right one
- **Improves safety** — limits what operations are available per page

---

## Tech Stack

| Technology | Purpose |
|---|---|
| **TypeScript** | Primary language |
| **Node.js 24** | Runtime |
| **@google-cloud/functions-framework** | HTTP function handling (Cloud Run compatible) |
| **@modelcontextprotocol/sdk** | MCP server and Streamable HTTP transport |
| **Zod** | Input schema validation for tool parameters |
| **Axios** | HTTP client for auth validation (and future data access) |
| **dotenv** | Environment variable loading |
| **Docker** | Containerization (multi-stage build) |
| **Google Cloud Run** | Deployment platform |
| **Google Artifact Registry** | Docker image storage |