Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Model Context Protocol (MCP) Explained

By Kokil Thapa | Last reviewed: September 2026

Model Context Protocol (MCP) Explained starts with a problem every team hits after the first LLM demo ships. Your chatbot works in the IDE, but it cannot read your MySQL orders table, call your Khalti webhook, or pull live data from a Laravel admin panel without brittle, one-off glue code. MCP is an open standard—originally published by Anthropic—that replaces those ad-hoc integrations with a predictable client-server contract. If you already ship REST APIs for business systems, MCP gives LLM hosts the same kind of plug-in surface, but purpose-built for tools, resources, and prompts rather than human-facing HTTP endpoints.

What is the Model Context Protocol (MCP) and why does it matter?

MCP defines how an AI application talks to the outside world. Before MCP, each editor, agent framework, and SaaS product invented its own plugin format. One team wrote OpenAI function schemas by hand. Another built a Slack bot with raw cURL. A third hard-coded Postgres queries inside a Python script only Claude Desktop could reach.

That fragmentation wastes engineering time. It also creates security blind spots, because every integration handles auth, logging, and rate limits differently. MCP standardises the wire format so one MCP server—a small process exposing tools and resources—can plug into Claude Desktop, Cursor, VS Code extensions, and other MCP-compatible hosts without rewriting the backend logic.

For a custom software shop, the practical win is separation of concerns. Your Laravel application stays the source of truth for business rules. The MCP server exposes read-only order lookups or safe admin actions. The LLM host decides when to call them based on user intent. You are not embedding SQL inside prompt templates anymore.

MCP is not a replacement for your public REST API. Customers and mobile apps still consume HTTP endpoints documented in OpenAPI. MCP is the integration layer between an LLM host and your internal systems—similar in spirit to how ODBC standardised database drivers, but oriented toward agent workflows. Anthropic open-sourced the specification; the community maintains SDKs and reference servers on GitHub. See the official specification at modelcontextprotocol.io for normative details.

MCP Architecture OverviewMCP HostCursor, Claude Desktop, IDE agentMCP ClientJSON-RPC session inside hostMCP Server ADatabase toolsMCP Server BGit + filesMCP Server CREST bridge
Model Context Protocol (MCP) explained: one host runs multiple clients, each connecting to an independent MCP server.

The three MCP primitives

Every MCP server advertises up to three capability types. Understanding them prevents you from exposing too much power to the model.

  • Tools — Callable functions the model can invoke. Example: create_support_ticket or search_orders_by_phone. Tools accept structured arguments and return structured results.
  • Resources — Readable data URIs the model can fetch. Example: order://12345/summary or a file path exposed as a resource template. Resources are read-oriented; they do not mutate state by convention.
  • Prompts — Pre-built prompt templates the host can surface to users. Example: a "draft legal intake summary" prompt wired to your firm's schema.

On legal-tech portals I have worked on—booking flows, document uploads, payment status—the distinction matters. You expose order status as a resource. You expose "create appointment hold" as a tool with strict validation. You never give the model raw SQL access as a tool unless you enjoy 3 a.m. incident calls.

How does Model Context Protocol (MCP) communication work on the wire?

MCP messages use JSON-RPC 2.0. The client opens a session, negotiates protocol version and capabilities, then exchanges lifecycle messages. Tool calls follow a request-response pattern the host mediates: the model proposes a tool name and arguments; the host asks the MCP client to execute; the server runs the handler and returns JSON the model reads on the next turn.

Two transports dominate in 2026. stdio launches the MCP server as a child process—stdin and stdout carry JSON-RPC frames. Desktop hosts like Claude Desktop and many IDE integrations prefer this model because it isolates crashes and simplifies local dev. Streamable HTTP (and the older SSE transport) suit remote servers behind auth—useful when your MCP server runs on the same Ubuntu box as a Laravel app but the host runs on a developer laptop.

A typical local config entry in a host JSON file looks like this:

{
  "mcpServers": {
    "company-orders": {
      "command": "node",
      "args": ["/opt/mcp/orders-server/dist/index.js"],
      "env": {
        "LARAVEL_API_BASE": "https://internal.example.com/api",
        "MCP_API_TOKEN": "rotate-this-secret"
      }
    }
  }
}

The host spawns the process, completes the MCP handshake, lists tools via tools/list, and caches schemas. When the user asks "show unpaid invoices for PAN 123456789", the model selects a tool, the client sends tools/call, and the server hits your backend. For debugging payloads, a JSON formatter saves time—you will stare at nested argument objects often.

MCP Tool Call FlowUserLLM HostModel + clientMCP ServerYour APILaravel / DB1. Prompt2. Plan tool3. tools/call4. HTTP queryResponse path (reverse)API returns JSON rowsServer wraps result for MCPHost feeds result to modelUser sees grounded answer
Model Context Protocol tool call lifecycle: the host always sits between the model and your production backend.

Handshake and capability negotiation

After connect, the client sends initialize with its protocol version. The server responds with supported capabilities—whether it exposes tools, resources, prompts, or logging. Either side can send notifications when lists change; for example, when you deploy a new tool without restarting the host.

Version mismatches are a common dev pain point. Pin the SDK version in your server package and test against your target host monthly. The specification evolves; the GitHub specification repo publishes changelog entries you should read before upgrading production servers.

How do you connect MCP to Laravel, PHP, and existing production systems?

Official MCP SDKs target TypeScript, Python, Java, Kotlin, and C# as of 2026. PHP does not ship a first-party SDK yet. In practice, Laravel teams pick one of three patterns—each maps cleanly to how I already integrate LLM APIs on client projects.

Pattern 1: Thin MCP server, fat Laravel API

This is the pattern I recommend most often. Write a small Node.js MCP server using the official TypeScript SDK. Each tool handler calls your existing Laravel Sanctum-protected internal API. Business logic stays in Form Requests, policies, and Eloquent models you already test.

  1. Create an internal API route group in Laravel 12 or 13 with token auth and strict rate limits.
  2. Build tool schemas that mirror safe, idempotent operations—search, summarise, export—not arbitrary writes.
  3. Implement the MCP server with one handler file per domain: orders, leads, documents.
  4. Register the server in the host config and test with a fixed prompt suite before giving access to staff.

Example Laravel internal endpoint the MCP server might call:

// routes/api.php — internal MCP bridge only
Route::middleware(['auth:sanctum', 'throttle:mcp'])->prefix('internal/mcp')->group(function () {
    Route::get('/orders/search', [McpOrderController::class, 'search']);
    Route::get('/orders/{order}/summary', [McpOrderController::class, 'summary']);
});

Keep controllers thin. Return JSON shaped for the model—short strings, redacted PII, explicit field names. Your public API versioning rules from rate limiting and abuse prevention apply here too; MCP traffic is still HTTP.

Pattern 2: Database read-only MCP server

Some teams expose a read replica directly through a Postgres or MySQL MCP reference server for analytics questions. Fast to stand up; dangerous if schemas include PII columns. Restrict views, use read-only credentials, and filter at the SQL view layer—not in prompt instructions. Prompts are not access control.

Pattern 3: Remote HTTP MCP for shared teams

When five developers need the same company tools, run the MCP server on Ubuntu behind Nginx with OAuth or mTLS. Streamable HTTP transport lets hosts connect without spawning local processes. This mirrors how you would deploy any internal microservice. Your Linux administration habits—UFW, fail2ban, log rotation—apply unchanged.

For AI-specific delivery—wiring MCP into workflows, host selection, and governance—see AI integration and automation services. The protocol is the easy part; scoping safe tools is the work.

How does MCP compare to REST APIs, webhooks, and custom function calling?

Teams often ask whether MCP replaces OpenAI-style function calling or their existing REST layer. It does not replace REST for product clients. It standardises the adapter between LLM hosts and backends so you write tool definitions once.

ApproachBest forWeaknessOps burden
Custom REST + hand-written schemas per hostSingle-vendor prototypeRe-implement for each IDE or agentHigh duplication
OpenAI function calling onlyChatGPT-centric appsNot portable to Claude Desktop or CursorMedium
MCP serversMulti-host agent toolingExtra process to deploy and secureMedium, but DRY
Direct DB access from promptsNever in productionNo audit trail, full data leak riskDeceptively "low" until incident

MCP wins when the same integration must serve multiple hosts—legal intake drafting in Cursor for devs, Claude Desktop for ops, a future internal agent for client support. It loses when you only embed chat in one SaaS product with one model provider; a direct API integration may stay simpler.

Relate this to how models consume context in the first place. If you have not read it yet, tokens, embeddings, and context windows explains why tool results still compete with conversation history for space—and why concise MCP responses matter.

MCP vs Custom Glue CodeWithout MCPHost A → custom API AHost B → custom API BHost C → custom API C3 schemas to maintain3 auth pathsWith MCPHost A ↘Host B → MCP ServerHost C ↗One tool schemaOne audit surface
Model Context Protocol (MCP) explained as a deduplication layer: multiple LLM hosts share one server implementation.

What security and governance rules should you enforce for MCP in production?

MCP moves power closer to the model. That is the risk. A misconfigured tool with write access can cancel bookings, refund payments, or exfiltrate client documents from a law-firm portal. Treat MCP servers like privileged microservices, not like developer convenience scripts.

Minimum production checklist

  • Least privilege — Separate DB users, API tokens, and OS accounts per MCP server. Scope tokens to explicit routes.
  • Human confirmation for mutations — Require host UI approval before destructive tools run. Many hosts support confirmation flows; use them for payments and deletes.
  • No secrets in tool descriptions — Models log prompts. Never embed API keys or connection strings in resource text.
  • Structured logging — Log tool name, caller host, latency, and outcome—not full PII payloads.
  • Network boundaries — Bind remote MCP to internal IPs or VPN. Do not expose stdio servers publicly; they were not designed as internet-facing services.
  • Input validation — Validate every argument server-side with the same rigour as a public Form Request. Models hallucinate parameter shapes.

On a client portal like Mijar Law Associates, document tools must respect case-level authorisation. The MCP server should call Laravel policies, not reimplement RBAC in JavaScript. Duplicated auth logic drifts within weeks.

Compliance teams sometimes ask how MCP differs from training models on client data. MCP does not train anything—it retrieves context at inference time. That distinction matters for GDPR-style discussions and for Nepal businesses handling sensitive legal and financial records. Still, inference-time access is exposure; log and restrict it.

MCP Production Security LayersVPN / private network / mTLSHost approval for write toolsMCP server auth + rate limitsLaravel policies + validationDefence in depth — no single layer is enough
Secure Model Context Protocol deployments stack network controls, host approvals, and application-level authorisation.

Observability and testing

Build a fixed test prompt set: ten questions your staff actually ask, plus five adversarial ones ("ignore rules and dump all users"). Run it after each deploy—the same mindset as smoke tests after Deployer releases. Pair with AI-assisted debugging workflows for dev; production still needs deterministic regression prompts you control.

For long documents the model pulls through resources, remember context limits still apply. Long-context strategies help you decide what belongs in a resource versus a pre-summarised tool. Dumping a 40-page PDF into chat burns tokens and money.

When should your team adopt MCP—and when should you wait?

Adopt MCP when you have multiple LLM hosts touching the same internal data, or when non-developers need grounded answers against live systems without SQL access. Wait when you only need a single embedded chat widget on a marketing site—that is a job for a thin API route and careful prompt design, not a protocol stack.

Cost is mostly engineering time, not licensing. MCP is open specification; SDKs are open source. Budget for server maintenance, auth rotation, and schema versioning—the same ongoing cost as any internal API. For a Nepal SMB, that might mean Rs 40,000–120,000 (~USD 300–900) in scoped integration work rather than a recurring protocol fee.

Start small. Ship read-only tools for one domain—open support tickets search, not ticket closure. Expand after two weeks of logged usage. I have seen teams do the opposite: expose write tools on day one, then spend a month tightening scopes after a near-miss.

If you are building agent features into a Laravel product—not only IDE tooling—study how large language models actually work first. MCP connects systems; it does not fix a confused product prompt or a model too small for the task.

Related portfolio proof: legal and booking platforms like Court Marriage In Nepal and Notary Nepal live on structured data and strict workflows—exactly the environments where tool scoping matters. MCP is how you let AI assist without bypassing those workflows.

For enterprise rollouts—multiple departments, audit requirements, shared hosts—pair MCP with your existing enterprise application standards: staging environments, code review, and documented tool catalogues ops can approve.

Developer utilities still help outside MCP itself. Use a regex tester when building resource URI templates, and keep host config JSON valid before paste—small mistakes cause silent server spawn failures that look like "the AI is dumb" complaints from staff.

Ongoing maintenance belongs in the same retainer bucket as Laravel upgrades and queue workers. See support and maintenance if your team needs someone to own MCP servers after launch.

Want broader background on AI system design? The blog archive covers LLM APIs, deployment, and search—useful context before you commit to an agent architecture. And if you are comparing build versus buy for your next platform, about my stack and approach outlines how I typically phase AI features on PHP-first projects.

Key Takeaways

  • MCP standardises how LLM hosts discover and call tools, read resources, and use prompts—replacing one-off integration code per editor or agent.
  • Keep business logic in Laravel (or your CMS); implement MCP as a thin server that calls your existing authenticated internal APIs.
  • Use stdio for local dev, Streamable HTTP for shared remote servers—both speak JSON-RPC, but security models differ sharply.
  • Treat MCP tools as privileged microservices: least privilege, validation, logging, and human confirmation on writes.
  • Adopt when multiple hosts need the same data; skip when a single embedded chat widget with one REST endpoint is enough.
  • Read the official specification and pin SDK versions—MCP evolves, and silent handshake mismatches waste afternoons.

People Also Ask

Is Model Context Protocol only for Claude?

No. Anthropic introduced MCP, but the specification is open. Cursor, VS Code extensions, and other agent hosts implement MCP clients. Any model behind those hosts can use MCP tools—the protocol sits below the model layer. Your server code stays host-agnostic if you stick to the spec.

Do I need to rewrite my Laravel app to use MCP?

No. The practical path is an MCP server—often Node.js with the official TypeScript SDK—that calls Laravel routes you add or routes you already expose internally. Controllers, policies, and Eloquent stay unchanged. You are adding an adapter, not migrating frameworks.

How is MCP different from RAG?

RAG retrieves static or embedded documents to augment prompts. MCP executes live tools and reads current resources at request time. Many production agents combine both: vector search for knowledge-base articles, MCP tools for "what is the status of order 9912 right now?"

Can MCP servers run in production on shared hosting?

Stdio MCP fits local machines and developer workstations, not typical shared PHP hosting. Remote HTTP MCP needs a always-on process—VPS, container, or dedicated worker—similar to a Laravel queue worker. Budget for Linux ops, not cPanel-style shared plans.

Ship MCP integrations that respect your production data

Model Context Protocol (MCP) Explained boils down to a simple idea: one standard plug-in surface between LLM hosts and the systems you already run. The protocol is approachable; the hard part is scoping safe tools, wiring auth correctly, and keeping Laravel as the authority for business rules. Start read-only, log every call, and expand only when real staff prompts prove the need.

If you want MCP connected to a Laravel portal, WooCommerce store, or internal API without exposing client data to ad-hoc scripts, contact us to plan a phased rollout—or explore AI integration and automation for the full delivery path from tool design to production hardening.

Frequently Asked Questions

MCP is an open JSON-RPC standard that lets LLM hosts connect to external data and actions through MCP servers, so AI can query databases and run tools without one-off glue code per vendor.

Before MCP, every editor, agent framework, and SaaS product invented its own plugin format—OpenAI function schemas, raw cURL bots, hard-coded SQL in scripts. That fragmentation wastes engineering time and creates security blind spots because each integration handles auth, logging, and rate limits differently. MCP standardises the wire format so one MCP server can plug into Claude Desktop, Cursor, VS Code extensions, and other compatible hosts without rewriting backend logic. For a custom software shop, the practical win is separation of concerns: your Laravel application stays the source of truth, the MCP server exposes safe lookups or admin actions, and the LLM host decides when to call them based on user intent.

Tools are callable functions the model invokes—create_support_ticket or search_orders_by_phone—with structured arguments and results. Resources are readable data URIs the model fetches, such as order://12345/summary; they are read-oriented and do not mutate state by convention. Prompts are pre-built prompt templates the host surfaces to users, like a draft legal intake summary wired to your firm's schema. On legal-tech portals with booking flows, document uploads, and payment status, you expose order status as a resource, create appointment hold as a tool with strict validation, and never give the model raw SQL access as a tool unless you want 3 a.m. incident calls.

MCP messages use JSON-RPC 2.0. The client opens a session, negotiates protocol version and capabilities, then exchanges lifecycle messages. Tool calls follow a request-response pattern the host mediates: the model proposes a tool name and arguments, the host asks the MCP client to execute, the server runs the handler and returns JSON the model reads on the next turn. After connect, the client sends initialize with its protocol version; the server responds with supported capabilities—tools, resources, prompts, or logging. Either side can send notifications when lists change, for example when you deploy a new tool without restarting the host.

stdio launches the MCP server as a child process where stdin and stdout carry JSON-RPC frames. Desktop hosts like Claude Desktop and many IDE integrations prefer this because it isolates crashes and simplifies local development. Streamable HTTP and the older SSE transport suit remote servers behind auth—useful when your MCP server runs on the same Ubuntu box as a Laravel app but the host runs on a developer laptop. For shared teams where five developers need the same company tools, run the MCP server on Ubuntu behind Nginx with OAuth or mTLS and use Streamable HTTP so hosts connect without spawning local processes.

Official MCP SDKs target TypeScript, Python, Java, Kotlin, and C# as of 2026; PHP does not ship a first-party SDK yet. The pattern I recommend most often is a thin Node.js MCP server using the official TypeScript SDK, with each tool handler calling your existing Laravel Sanctum-protected internal API. Business logic stays in Form Requests, policies, and Eloquent models you already test. Create an internal API route group in Laravel 12 or 13 with token auth and strict rate limits, build tool schemas that mirror safe idempotent operations, and implement the MCP server with one handler file per domain. Alternative patterns include a read-only database MCP server via Postgres or MySQL reference servers, or remote HTTP MCP behind Nginx for shared team access.

No. Customers and mobile apps still consume HTTP endpoints documented in OpenAPI. MCP is the integration layer between an LLM host and your internal systems—similar in spirit to how ODBC standardised database drivers, but oriented toward agent workflows. It standardises the adapter between LLM hosts and backends so you write tool definitions once rather than re-implementing for each IDE or agent. MCP wins when the same integration must serve multiple hosts; it loses when you only embed chat in one SaaS product with one model provider, where a direct API integration may stay simpler.

Custom REST plus hand-written schemas per host works for single-vendor prototypes but forces re-implementation for each IDE or agent, creating high duplication. OpenAI function calling alone suits ChatGPT-centric apps but is not portable to Claude Desktop or Cursor. MCP servers serve multi-host agent tooling with medium ops burden—an extra process to deploy and secure—but you write integration logic once. Direct database access from prompts is deceptively low effort until an incident: no audit trail and full data leak risk. MCP is a deduplication layer where multiple LLM hosts share one server implementation.

Treat MCP servers like privileged microservices, not developer convenience scripts. Enforce least privilege with separate DB users, API tokens, and OS accounts per server, scoped to explicit routes. Require human confirmation in the host UI before destructive tools run—payments and deletes especially. Never embed API keys or connection strings in tool descriptions because models log prompts. Log tool name, caller host, latency, and outcome—not full PII payloads. Bind remote MCP to internal IPs or VPN; stdio servers were not designed as internet-facing services. Validate every argument server-side with the same rigour as a public Form Request because models hallucinate parameter shapes. On client portals, MCP servers should call Laravel policies, not reimplement RBAC in JavaScript.

No. MCP does not train anything—it retrieves context at inference time. That distinction matters for GDPR-style discussions and for Nepal businesses handling sensitive legal and financial records. Compliance teams sometimes ask this explicitly. Still, inference-time access is exposure; you must log and restrict it. A misconfigured tool with write access can cancel bookings, refund payments, or exfiltrate client documents from a law-firm portal. MCP moves power closer to the model, which is exactly why governance cannot be an afterthought.

Adopt when multiple LLM hosts touch the same internal data, or when non-developers need grounded answers against live systems without SQL access. Wait if you only need a single embedded chat widget on a marketing site—that is a thin API route and careful prompt design, not a protocol stack. Start small with read-only tools for one domain, expand after two weeks of logged usage. I have seen teams expose write tools on day one and spend a month tightening scopes after a near-miss.

MCP is an open specification with open-source SDKs—no licensing fee. Budget mostly engineering time: server maintenance, auth rotation, and schema versioning, similar to any internal API. For a Nepal SMB, scoped integration work often runs Rs 40,000–120,000 (~USD 300–900) rather than a recurring protocol fee.

Write a small Node.js MCP server with the TypeScript SDK; each tool handler calls your Laravel Sanctum-protected internal API under a dedicated route group with throttle:mcp middleware. Keep controllers thin and return JSON shaped for the model—short strings, redacted PII, explicit field names. Register the server in the host JSON config with command, args, and env vars like LARAVEL_API_BASE and MCP_API_TOKEN. Build one handler file per domain—orders, leads, documents—and test with a fixed prompt suite before giving staff access. Your public API versioning, rate limiting, and abuse prevention rules apply here too because MCP traffic is still HTTP hitting your backend.

Build a fixed test prompt set: ten questions your staff actually ask, plus five adversarial ones like ignore rules and dump all users. Run it after each deploy—the same mindset as smoke tests after Deployer releases. Pin the SDK version in your server package and test against your target host monthly because version mismatches are a common dev pain point; read the GitHub specification repo changelog before upgrading production servers. For debugging payloads, a JSON formatter saves time because you will stare at nested argument objects often. Pair with AI-assisted debugging for development, but production still needs deterministic regression prompts you control.

Exposing write tools before read-only tools are proven is the biggest one—I have seen teams spend a month tightening scopes after a near-miss. Giving the model raw SQL access as a tool, embedding secrets in tool descriptions, and duplicating RBAC logic in the MCP server instead of calling Laravel policies all create incidents within weeks. Using prompts as access control on a read-only database MCP server is another trap; restrict views and filter at the SQL view layer instead. Dumping long documents through resources burns tokens and money because context limits still apply—pre-summarise via tools when possible. Skipping human confirmation flows for mutations on booking and payment workflows is reckless on any production portal.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: