Ops Lense
by qubydev
README.md
# Ops Lense
Ops Lense is a remotely hosted **Model Context Protocol (MCP) server for commerce operations**. It helps an operations specialist investigate stuck orders, understand what went wrong, and take the next safe action without needing an engineer for every incident.
This assignment intentionally focuses on one workflow in depth: **stuck-order investigation and remediation** across orders, payments, inventory, and fulfillment.
## What it demonstrates
An operator can ask an MCP-enabled AI client questions such as:
> Why is this paid order still stuck?
The AI can use Ops Lense to:
1. find the order;
2. inspect its operational timeline;
3. diagnose the likely failure from backend data;
4. determine how safely the proposed action can be performed;
5. preview and execute a bounded remediation after operator confirmation; or
6. send a high-risk action to a manual-review queue instead of executing it.
The MCP is therefore the core product interface, not an additional integration around a separate application.
## Safety model
Not every commerce operation should have the same level of AI autonomy. Ops Lense separates actions into three categories.
| Category | Behavior | Examples |
| --- | --- | --- |
| **Instant** | Read-only investigation can run immediately | Search orders, view timeline, diagnose an order, view statistics |
| **Confirmation required** | MCP previews the change first and executes only after explicit operator approval | Resync a missing inventory reservation |
| **Manual review only** | MCP cannot execute the action; it creates a pending review request | Refund payment, cancel a shipped order, override fulfillment, adjust inventory |
### Confirmation flow
`resync_inventory_reservation` is a guarded write operation.
First call:
```text
confirmed=false
```
The server validates the order and returns the proposed effect without changing the database.
After the operator explicitly approves the action, the client may call:
```text
confirmed=true
```
The server then performs the bounded mutation and records an audit entry.
### Manual-review flow
Critical actions are intentionally unavailable as direct MCP mutations. `request_manual_review` creates a `pending_review` audit entry instead.
The separate process where another operator reviews, approves, and executes those requests is deliberately outside the assignment scope. Pending requests remain visible through `list_manual_reviews`.
## MCP tools
| Tool | Safety | Purpose |
| --- | --- | --- |
| `search_orders` | Instant | Find recent orders, optionally filtered by status |
| `get_order_timeline` | Instant | View the chronological operational history of an order |
| `diagnose_order` | Instant | Detect supported stuck-order conditions from payment and operational evidence |
| `get_order_stats` | Instant | View aggregate order counts and revenue by status |
| `resync_inventory_reservation` | Confirmation required | Preview and repair a missing inventory reservation after explicit approval |
| `request_manual_review` | Manual review | Queue a high-risk operation without executing it |
| `list_manual_reviews` | Instant | View outstanding manual-review requests |
## MCP resource
Ops Lense exposes one operational resource:
```text
ops://action-policy
```
It describes the three action categories and the rules an MCP client should follow when choosing or executing tools.
I chose a resource rather than an MCP prompt because this is stable operational policy that should be available regardless of how the user phrases their request. A dedicated prompt would add little value to this deliberately narrow workflow.
## Example end-to-end workflow
A representative incident is an order where payment was captured successfully but the inventory reservation step is missing.
1. The operator asks why an order is stuck.
2. The AI uses `search_orders` if it needs to locate the order.
3. It calls `get_order_timeline` to inspect what has happened.
4. It calls `diagnose_order` to correlate the payment and operational state.
5. The diagnosis identifies `INVENTORY_RESERVATION_MISSING` and recommends `resync_inventory_reservation`.
6. The AI calls the tool with `confirmed=false` and shows the proposed remediation to the operator.
7. The operator approves it.
8. The AI calls the tool again with `confirmed=true`.
9. The MCP performs the remediation and writes an audit record.
10. The AI calls `get_order_timeline` again to verify the resulting state.
A high-risk request follows a different path. For example, if an operator asks for a refund, the MCP creates a manual-review request rather than modifying payment state. The request can then be inspected with `list_manual_reviews`.
This gives the demo one coherent story covering **investigation → diagnosis → human confirmation → mutation → verification → escalation**.
## Architecture
```text
MCP-enabled AI client
|
| Streamable HTTP
v
Ops Lense MCP
|
+-- Investigation tools
+-- Diagnostic logic
+-- Safety / action policy
+-- Guarded actions
|
v
Neon PostgreSQL
synthetic commerce data
```
Technology:
- TypeScript
- Bun for local development and scripts
- Node.js 24 on Heroku
- Model Context Protocol server packages
- Express HTTP transport
- Neon PostgreSQL
- Zod input validation
The synthetic data models the minimum backend systems needed for the workflow: customers, orders, payments, inventory, fulfillment, operational events, investigation history, and action audit records.
## Run locally
### Prerequisites
You need:
- Bun
- a PostgreSQL database; Neon works well for the hosted demo
### 1. Install dependencies
```bash
bun install
```
### 2. Configure environment variables
Create a `.env` file in the project root:
```env
DATABASE_URL=postgresql://YOUR_DATABASE_URL
MCP_AUTH_TOKEN=YOUR_STRONG_RANDOM_TOKEN
PORT=3000
```
### 3. Create the synthetic database
```bash
bun scripts/setup-db.ts
```
This command drops and recreates the assignment tables. **Do not run it against a database containing data you need to keep.**
### 4. Seed demo data
```bash
bun scripts/seed-db.ts
```
All seeded customers, orders, payments, inventory, and fulfillment records are synthetic.
### 5. Build and start the MCP server
```bash
bun run build
bun run start
```
`bun run build` compiles TypeScript into `dist/`. The start command then runs the compiled server with Node, matching the Heroku runtime path.
The local MCP endpoint is:
```text
http://localhost:3000/mcp
```
## Deploy to Heroku
The repository includes a `Procfile` that starts the web dyno with `npm start`. Heroku builds the TypeScript project and runs the compiled Node.js server.
### 1. Create the Heroku app
```bash
heroku create YOUR_APP_NAME
```
### 2. Configure the database
Set the PostgreSQL connection string and a strong bearer token used to protect the MCP endpoint:
```bash
heroku config:set DATABASE_URL="YOUR_DATABASE_URL" MCP_AUTH_TOKEN="YOUR_STRONG_RANDOM_TOKEN" -a YOUR_APP_NAME
```
Heroku provides `PORT` automatically, so you do not need to configure it manually.
### 3. Deploy
```bash
git push heroku HEAD:main
```
During deployment Heroku installs the Node dependencies and runs the `build` script. The web dyno then starts:
```text
node dist/index.js
```
The hosted MCP endpoint will be:
```text
https://YOUR_APP_NAME.herokuapp.com/mcp
```
If your Heroku app uses a custom domain, use that domain with `/mcp` instead.
### 4. Verify the deployment
```bash
heroku logs --tail -a YOUR_APP_NAME
```
You should see the MCP server start and bind to Heroku's assigned port.
The synthetic database can be initialized before deployment from your local machine using the same `DATABASE_URL`, or by running the setup and seed scripts as one-off Heroku commands if Bun is available in that environment. For the simplest deployment path, initialize and seed Neon locally before deploying the server.
## Connect from an AI client
Ops Lense uses a remote HTTP MCP endpoint. In an MCP client that supports remote/Streamable HTTP servers, add the endpoint and bearer token:
```json
{
"serverUrl": "http://localhost:3000/mcp",
"headers": {
"Authorization": "Bearer YOUR_STRONG_RANDOM_TOKEN"
}
}
```
For a deployed instance, replace the local URL with the hosted MCP URL and use the same token configured as `MCP_AUTH_TOKEN` on the server.
After connecting, the client should discover the tools and `ops://action-policy` resource automatically.
You can then start naturally, for example:
```text
Show me recent orders that may need attention.
```
```text
Why is this order stuck? Investigate it and tell me what we can safely do.
```
```text
Show me all actions currently waiting for manual review.
```
For confirmation-required operations, the AI should present the preview to the operator and obtain explicit approval before making the second tool call with `confirmed=true`.
## Connect with MCP Inspector
MCP Inspector is useful for testing the server independently of a chat client.
With the local server running:
```bash
npx @modelcontextprotocol/inspector
```
In Inspector, connect to:
```text
http://localhost:3000/mcp
```
You can then inspect the discovered tools/resource and invoke the workflow manually.
## Verification
Type-check the project with:
```bash
npm run typecheck
```
Run the focused Vitest integration suite against the configured synthetic database:
```bash
npm test
```
The tests in `tests/operations.test.ts` create isolated temporary records, exercise the real tool functions against PostgreSQL, and remove those records afterward. They verify:
- captured payment with a missing reservation produces `INVENTORY_RESERVATION_MISSING`;
- terminal orders are not diagnosed as active inventory failures;
- `confirmed=false` performs no mutation;
- `confirmed=true` performs the bounded inventory remediation and records an audit entry;
- repeating an already completed resync is a safe no-op;
- a refund request is queued for review without changing payment state;
- duplicate pending review requests are suppressed.
The suite currently contains 8 integration tests. A successful run reports `8 passed`.
These tests are intentionally focused on the workflow and safety boundaries rather than broad coverage metrics.
## Key product decisions
### Keep the workflow narrow
The assignment does not attempt to build a complete commerce backend. Stuck-order operations were selected because they provide a compact workflow involving multiple systems, diagnosis, remediation, safety, and verification.
### Give AI useful autonomy, not unrestricted write access
Making every operation read-only would leave the operator dependent on another system to resolve even simple incidents. Allowing every mutation would create unnecessary operational risk.
The three-tier model provides a middle ground: investigation is automatic, bounded remediation requires operator confirmation, and consequential actions remain behind manual review.
### Keep critical actions out of MCP execution
Refunds and similar operations could technically be represented as database mutations in this synthetic project, but doing so would demonstrate the wrong production behavior. The MCP instead creates a review request and makes the boundary explicit.
### Keep the MCP surface small
Each exposed tool has a clear role in the chosen workflow. The goal is for an AI client to select tools reliably, not to maximize the number of available tools.
## Scope and assumptions
Included:
- synthetic commerce data
- order investigation
- deterministic diagnosis of the supported stuck-order condition
- guarded inventory remediation
- audit logging
- manual-review queue
- remotely accessible MCP interface
Intentionally excluded:
- frontend/admin dashboard
- real customer data
- production payment or warehouse credentials
- user accounts, sessions, OAuth, and role-based access control
- direct refund execution
- manual-review approval/execution UI
- complete commerce backend
- broad returns, fraud, catalog, and customer-support workflows
The hosted assignment server uses a single bearer token to avoid exposing the MCP publicly. For a production system, identity-aware authentication, authorization/RBAC, secret rotation, stronger concurrency controls, provider-specific integrations, observability, and a complete review workflow would need to be added.
## Repository structure
```text
src/
index.ts
db.ts
resources.ts
tools/
diagnose-order.ts
get-stats.ts
get-timeline.ts
list-manual-reviews.ts
request-manual-review.ts
resync-inventory.ts
search-orders.ts
scripts/
setup-db.ts
seed-db.ts
tests/
operations.test.ts
vitest.config.ts
```
## AI worklog
This section should contain the actual AI usage from the assignment before submission:
- AI coding tools and exact models used
- why each model was chosen for its task
- how the work was planned and decomposed
- responsibilities handled by AI versus the developer
- important prompts/context supplied to AI
- at least one AI suggestion that was rejected or substantially changed
- how AI-generated work was reviewed and verified
- remaining risks or unfinished work
One product decision that changed during development was the treatment of consequential operations. Rather than exposing refunds and similar critical actions as executable MCP tools, they were moved behind a manual-review queue. This preserves useful AI autonomy while keeping financially or operationally consequential decisions outside direct model execution.
## Submission
The final submission should include:
- hosted MCP URL
- source repository URL
- this README
- verification/tests for the important workflow behavior
- completed AI worklog
- 4–5 minute asynchronous demo
The demo should prioritize the actual product workflow over code walkthroughs: **investigate an order, diagnose it, preview a safe remediation, confirm it, verify the result, then show how a critical action is routed to manual review.**
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo issues