# How to Set Up and Integrate the MCP Server with Prompt-Optimizer: A Complete Guide

> Learn to set up and integrate the MCP server with prompt-optimizer. Clone the repo, configure .env, and launch the Express service to expose AI model capabilities via REST API.

- Repository: [且炼时光/prompt-optimizer](https://github.com/linshenkx/prompt-optimizer)
- Tags: how-to-guide
- Published: 2026-02-23

---

**Setting up the MCP server involves cloning the monorepo, configuring environment variables in `packages/mcp-server/.env`, and launching the Express service via `pnpm -F @prompt-optimizer/mcp-server dev` to expose AI model capabilities via REST API.**

The **MCP (Model Context Protocol) server** is the backend component that powers `linshenkx/prompt-optimizer`'s AI-model services through a REST/HTTP interface. When you set up and integrate the MCP server with prompt-optimizer, you enable any frontend package—whether the web UI, browser extension, or desktop app—to communicate with large language models through a unified SDK layer. This guide walks you through the complete installation, configuration, and integration process using the actual source code from the repository.

## What Is the MCP Server?

The MCP server is an Express-based HTTP service located in `packages/mcp-server` that wraps the `@modelcontextprotocol/sdk`. It translates incoming HTTP requests into standardized model context protocol calls, allowing prompt-optimizer components to interact with OpenAI, Claude, and other providers without hardcoding provider-specific logic.

Key architectural components include:

- **[`src/start.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/start.ts)** – The entry point that boots the Express application, loads environment configuration, and starts the HTTP listener.
- **[`src/index.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/index.ts)** – Exposes the `createApp()` factory function used by the start script and test suites.
- **[`src/config/models.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/config/models.ts)** – TypeScript interfaces defining valid environment variables and runtime options.
- **[`src/config/environment.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/config/environment.ts)** – Parses `.env` files using `dotenv` and validates them against the models.
- **`src/adapters`** – Contains translation layers ([`parameter-adapter.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/parameter-adapter.ts), [`language-service.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/language-service.ts), [`core-services.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/core-services.ts)) that bridge HTTP routes to the Model-Context SDK.

## Prerequisites and Repository Layout

Before you begin, ensure you have **Node.js 20+** and **pnpm** installed. The prompt-optimizer monorepo uses pnpm workspaces to manage multiple packages simultaneously.

Clone the repository and install dependencies:

```bash
git clone https://github.com/linshenkx/prompt-optimizer.git
cd prompt-optimizer
pnpm install

```

This command installs dependencies for all packages—including `core`, `ui`, `web`, `extension`, `desktop`, and the **mcp-server**—in one operation.

## Step-by-Step Setup Guide

### 1. Configure Environment Variables

Create the server-specific environment file by copying the example template:

```bash
cp packages/mcp-server/.env.example packages/mcp-server/.env

```

Edit `packages/mcp-server/.env` to include your LLM provider credentials:

```dotenv
MCP_PORT=4000
OPENAI_API_KEY=sk-your-key-here
MODEL_CONTEXT_ENDPOINT=https://api.openai.com/v1/
MCP_TIMEOUT=30000

```

The server validates these variables at startup using the validation logic in [`src/config/environment.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/config/environment.ts). Missing required keys will trigger a clear error message before the server attempts to bind to a port.

### 2. Launch the Development Server

Start the MCP server locally using the monorepo filter flag:

```bash
pnpm -F @prompt-optimizer/mcp-server dev

```

This executes the `dev` script defined in [`packages/mcp-server/package.json`](https://github.com/linshenkx/prompt-optimizer/blob/main/packages/mcp-server/package.json). The process loads [`src/start.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/start.ts), which calls `createApp()` from [`src/index.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/index.ts), registers CORS and JSON body parsing middleware, attaches the MCP adapter routes, and begins listening on the configured port.

You should see a startup banner in your terminal indicating the server is listening on `http://localhost:4000`.

### 3. Verify the Health Endpoint

Confirm the server is operational by querying the health check endpoint:

```bash
curl http://localhost:4000/health

```

A successful response returns:

```json
{ "status": "ok" }

```

This validates that the Express application in [`src/start.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/start.ts) has correctly initialized and that the environment configuration loaded without errors.

## Integrating with Other Components

Once running, other prompt-optimizer packages communicate with the MCP server through the `ModelContextClient` from `@modelcontextprotocol/sdk`.

### TypeScript Client Integration

Import the SDK client and initialize it with your MCP base URL:

```typescript
import { ModelContextClient } from '@modelcontextprotocol/sdk';

const client = new ModelContextClient({
  baseUrl: process.env.MCP_BASE_URL ?? 'http://localhost:4000',
});

// Send a prompt and receive a completion
const response = await client.runPrompt({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Optimize this prompt for clarity.' }],
});

console.log(response.choices[0].message.content);

```

The client automatically serializes the request, sends it to the MCP server's HTTP interface, and parses the LLM provider's response.

### Web UI Integration Example

In the web package (`packages/web`), configure the client using Vite environment variables:

```tsx
import { ModelContextClient } from '@modelcontextprotocol/sdk';

export function PromptPanel() {
  const client = new ModelContextClient({
    baseUrl: import.meta.env.VITE_MCP_URL, // Set in packages/web/.env
  });

  async function optimizeUserPrompt(userInput: string) {
    const result = await client.runPrompt({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: userInput }],
    });
    return result;
  }
}

```

Ensure `VITE_MCP_URL=http://localhost:4000` is set in `packages/web/.env` so the browser can reach the locally running MCP server.

## Production Deployment

### Docker Containerization

The repository root contains a `Dockerfile` that containerizes the MCP server for production:

```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY . .
RUN pnpm install && pnpm -F @prompt-optimizer/mcp-server build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/packages/mcp-server/dist ./dist
COPY packages/mcp-server/.env.example ./.env
EXPOSE 4000
CMD ["node", "dist/start.js"]

```

Build and run:

```bash
docker build -t prompt-optimizer-mcp .
docker run -p 4000:4000 --env-file .env prompt-optimizer-mcp

```

The production container executes [`dist/start.js`](https://github.com/linshenkx/prompt-optimizer/blob/main/dist/start.js), which calls the same `createApp()` function used in development but optimized through the TypeScript build process.

### Environment Management

For production deployments, provide secrets through your orchestration platform (Kubernetes secrets, AWS Parameter Store, etc.) rather than committing `.env` files. The server expects the same variable names (`MCP_PORT`, `OPENAI_API_KEY`, `MODEL_CONTEXT_ENDPOINT`) regardless of the deployment method.

## Summary

- The **MCP server** is an Express application in `packages/mcp-server` that exposes AI model access via HTTP using the `@modelcontextprotocol/sdk`.
- **Setup** requires cloning `linshenkx/prompt-optimizer`, running `pnpm install`, copying `.env.example` to `.env`, and launching with `pnpm -F @prompt-optimizer/mcp-server dev`.
- **Integration** happens through `ModelContextClient` instances pointing to the MCP URL; this pattern is used across the web, extension, and desktop packages.
- **Key source files** include [`src/start.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/start.ts) (bootstrap), [`src/index.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/index.ts) (`createApp()` export), and `src/adapters` (SDK translation layer).
- **Production deployment** is supported via Docker, with the build pipeline defined in the root `Dockerfile` and CI workflows in [`.github/workflows/docker.yml`](https://github.com/linshenkx/prompt-optimizer/blob/main/.github/workflows/docker.yml).

## Frequently Asked Questions

### What port does the MCP server use by default?

By default, the server listens on **port 4000** as defined in `packages/mcp-server/.env.example`. You can override this by setting `MCP_PORT` in your environment file or container orchestration configuration before starting the service.

### Can I run the MCP server without the rest of the monorepo?

While the server can technically start independently, it depends on shared build configurations and the `@modelcontextprotocol/sdk` peer dependency managed at the monorepo root. It is recommended to run `pnpm install` from the repository root to ensure all workspace links resolve correctly.

### How does the server handle authentication with LLM providers?

Authentication is handled entirely through environment variables. The [`src/config/environment.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/config/environment.ts) module loads your `OPENAI_API_KEY` (or other provider keys) into the application context. The adapters in [`src/adapters/core-services.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/adapters/core-services.ts) then inject these credentials into the SDK client instances when forwarding requests to external APIs.

### Where can I find the logging output for debugging?

The centralized logger in [`src/utils/logging.ts`](https://github.com/linshenkx/prompt-optimizer/blob/main/src/utils/logging.ts) writes to both the console and optional file outputs depending on your `LOG_LEVEL` environment setting. By default, startup messages and request errors print to stdout, with structured JSON logging available when `NODE_ENV=production`.