MCP: Model Context ProtocolBeginnerModule 02 — MCP architecture and components

What is an MCP server, and what capabilities does it expose?

Question 15 of 43 · Updated

On this page

Direct answer#

An MCP server is a software component that exposes supported capabilities through the Model Context Protocol. It receives protocol messages from compatible clients, advertises the capability types it supports, handles discovery and invocation requests, executes registered handlers and returns results in the appropriate protocol representation.

A server can expose tools (callable operations), resources (URI-identified information) and prompts (reusable message templates). It may support additional protocol features depending on the specification revision and its implementation. A server does not have to expose all three primitives, run a language model or be deployed on a remote machine.

The server is responsible for its capability contracts, correct execution, authorization and integration with underlying systems. The host coordinates the user's task and optional model; the client manages the protocol connection. The server implements the other side of that connection.

Learning continuity: Q16 introduced the host, and Q17 followed the client lifecycle. Q18 completes the architectural roles by looking at the server from its implementation boundary inward. Later questions cover multi-server isolation, downstream integration, individual primitives, Python and TypeScript SDK construction, and advanced security and deployment.

Verification scope: Prepared under the authorized offline research and changelog exceptions, using the historical MCP 2025-06-18 specification as a reference baseline rather than claiming it is the latest revision. Official links were not checked live. The standard-library Python exercise was syntax-compiled and executed on Python 3.13.5; all 12 checks passed. It is an in-memory server-side teaching fixture, not a complete MCP implementation. The MCP SDK and local Mermaid package were unavailable; real SDK interoperability, transport behavior and Mermaid rendering remain unverified.

1. Understand the server through a business example#

Imagine the retailer from earlier lessons has an existing inventory service. It stores product availability and applies business rules. The company wants its support assistant, developer assistant and operations dashboard to reuse an approved stock lookup.

Rather than expose the inventory database directly to each assistant, the inventory team builds an MCP server with a narrow stock tool. The tool receives a product identifier, obtains an authorized inventory record, and returns the result.

The same server might expose a readable return-policy resource and a reusable prompt for summarizing verified stock information.

A compatible host can discover these capabilities through its MCP client. It does not need to know whether the server retrieves inventory using SQL, a REST API or an internal SDK. The server is responsible for translating between its advertised capability contract and the underlying system.

This does not make the MCP server the authoritative inventory database. The business system still determines which stock is available and which records an authenticated actor may access.

Loading diagram…

The diagram shows logical responsibilities, not required classes or a mandatory deployment topology. A server can run as a local subprocess, a remote service or another supported deployment. Multiple clients may connect to one server deployment when its transport and session model allow it.

2. Host versus client versus server#

ComponentPrimary roleRetail example
HostCoordinates tasks, consent, model integration and contextSupport application
ClientHandles protocol communication with a particular serverInventory client session
ServerAdvertises capabilities and processes their requestsInventory MCP adapter
Downstream serviceOwns data, transactions and domain rulesInventory database/API
Optional modelInterprets or generates informationModel proposing a stock lookup

The server is not responsible for managing every host's conversation or choosing the next action in an agent loop. Its operation can be invoked by deterministic clients as well as model-driven hosts. The model does not gain database credentials simply because the host discovers a tool.

The server may implement model-backed operations or request supported client features such as sampling. Those are specific capability dependencies, not a requirement for every MCP server.

3. Typical internal server architecture#

A practical server implementation often has several logical layers.

LayerResponsibility
TransportReceive and send messages over the supported mechanism
Protocol/session layerHandle initialization, negotiated revision and message rules
Capability registryMaintain supported tools, resources, prompts and metadata
DispatcherRoute recognized methods to the correct handler
Validation and authorizationCheck inputs, actor, permitted operation and resource
Domain adapterInvoke a trusted downstream service or local business function
Result encoderConstruct the applicable success or error representation
Lifecycle and telemetryManage resources, deadlines, notifications, logs and cleanup

SDKs can implement much of the protocol and transport work. Developers supply the domain handlers and policies. For example, registering a typed Python function may allow an SDK to derive a tool input schema, but that function still needs to enforce business rules.

A server may keep these layers in one process for a small integration. A remote enterprise deployment might separate protocol workers from downstream services and identity infrastructure. The protocol does not prescribe one universal internal architecture.

4. What capabilities can a server expose?#

Tools: callable operations#

A tool is a named operation with an input contract. It can retrieve information, perform a calculation or request a permitted state change. Examples include stock lookup, ticket search, or an approved order cancellation.

A stock tool might advertise metadata such as:

JSON
{ "name": "stock", "description": "Return available units for an authorized SKU", "inputSchema": { "type": "object", "properties": { "sku": {"type": "string"} }, "required": ["sku"], "additionalProperties": false } }

This is an illustrative tool descriptor from the historical protocol family, not a complete tools/list response. The schema constrains the shape of input. It does not establish that the caller is permitted to access the SKU or that the result is current.

A stock lookup can be read-only, whereas a cancellation changes business state. Both are tools, but their authorization, confirmation, idempotency and recovery requirements can differ substantially.

Resources: readable information identified by URI#

A resource represents information that a client can read using the supported resource interface. A server might expose a policy document, catalog entry or another authorized data representation.

An illustrative resource descriptor is:

JSON
{ "uri": "policy://returns", "name": "Return policy", "description": "Applicable retail return policy", "mimeType": "text/plain" }

The URI scheme is application-defined. A client should use the server's supported resource interface rather than assume it can open every resource URI directly as a file or HTTP URL.

A resource need not be static. It can represent generated or changing information. Authorization must be checked when it is read, including when the client already knows its identifier. Some implementations also expose resource templates and support subscriptions or updates.

Prompts: reusable message templates#

A prompt provides a reusable interaction pattern. A server could offer a stock-summary template that accepts a SKU, returning appropriate messages for a host to display or use.

JSON
{ "name": "stock_summary", "description": "Prepare a stock-summary request", "arguments": [ { "name": "sku", "description": "Product identifier", "required": true } ] }

Retrieving a prompt is not equivalent to running a language model, calling a stock tool or verifying a business fact. The host chooses how to use the returned messages. Prompt contents remain external data subject to the host's instruction hierarchy and policy.

Compare the three primitives#

PrimitivePurposeRetail exampleTypical interaction pattern
ToolExecute a named operationLook up stockModel or application chooses an operation
ResourceRead identified informationReturn-policy documentApplication selects information
PromptObtain reusable messagesStock-summary templateUser selects a workflow template

The common model-controlled, application-controlled and user-controlled descriptions are interaction-design guidance, not exclusive invocation rules or authorization grants. Deterministic software may invoke tools, and resource or prompt access still requires suitable policy.

Later modules examine each primitive separately. Here the essential server-side distinction is between an operation handler, a data-reading handler and a message-template handler.

5. Registration, advertisement and discovery are different#

A server developer registers capabilities in its implementation. Registration associates a stable name or URI with a handler and the metadata required by the supported contract. An SDK may derive metadata from typed functions or provide explicit registration interfaces.

Advertisement occurs during initialization, when the server communicates the capability families and optional features it supports. For example:

JSON
{ "protocolVersion": "2025-06-18", "capabilities": { "tools": {}, "resources": {}, "prompts": {} }, "serverInfo": { "name": "retail-capabilities", "version": "1.0.0" } }

This is an illustrative initialization result, not an entire JSON-RPC response. Empty feature objects advertise support for their capability families without claiming additional optional flags such as listChanged.

Discovery is a later operation that returns descriptions of available capabilities, such as tools/list or resources/list. The server may filter its catalog according to applicable authorization and application policy. Even an advertised capability family may contain no accessible entries for a particular actor.

StageWhat happens
RegistrationDeveloper associates metadata and implementation
AdvertisementServer declares supported protocol features
DiscoveryClient requests available descriptors
Invocation or retrievalServer executes an approved handler or retrieves data

These stages must remain consistent. A server should not advertise unsupported features or discoverable operations that have no functional handler. A discovered entry is not a permission grant, and changes in the actor's authority must be enforced during execution rather than relying on an old discovery response.

When evolving capability contracts, preserve compatible names, meanings and schemas or document a migration. Changing a tool's business meaning while leaving its metadata unchanged can mislead consumers.

6. How a server processes a request#

Suppose the host requests stock for product A12. The client sends an appropriate tools/call request to the server.

JSON
{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "stock", "arguments": {"sku": "A12"} } }

The server parses and validates the applicable protocol message, checks its lifecycle state, recognizes the method and resolves the tool's registered handler. It verifies the relevant identity and permission, validates business arguments and obtains the stock count from its downstream service.

Loading diagram…

The diagram abstracts transport-level authentication, initialization and message schemas. A production implementation should use the correct authorization and error representation at the applicable boundary; not every denial is represented by the same MCP response type.

A possible successful tool result is:

JSON
{ "jsonrpc": "2.0", "id": 3, "result": { "content": [ {"type": "text", "text": "7"} ] } }

The matching identifier lets the client correlate the response. The business information is carried in the tool result, not in the request ID. This example uses text content for simplicity. Other content and structured output may be supported under the applicable revision and contract.

7. Downstream integration and business authorization#

An MCP server often wraps an existing API, database, file store or internal library. Its purpose is to expose a controlled capability rather than simply grant the host unrestricted access to the backend.

For a stock tool, an application might perform an authorized parameterized query scoped to a trusted tenant. The tenant must come from validated identity and application context, not from an arbitrary model-generated argument.

A downstream service should enforce the resource boundary and domain invariants independently. A host can hide a forbidden operation, but a malicious or misconfigured client may attempt it directly. The server must therefore enforce permissions at execution time.

For remote MCP deployments using the applicable historical OAuth authorization framework, tokens need to be validated for the intended protected resource and scope. Local stdio deployments still require appropriate process identity, filesystem permissions and secret isolation. Neither transport grants unlimited authority.

Use narrowly scoped credentials for downstream services. Do not blindly forward an MCP access token to an unrelated resource. A separate service identity or supported, properly constrained delegation mechanism may be required.

For side effects, an operation must satisfy business rules at the authoritative execution boundary. For example, reserving stock must enforce inventory constraints at commit time, not merely rely on an earlier lookup. The server should preserve enough outcome information for safe reconciliation if a response is lost.

Q23 will focus specifically on downstream integration. The security and reliability modules will cover the implementation details of authorization, idempotency and recovery.

8. Result handling, failures and notifications#

Server responses must preserve meaningful distinctions between communication failures and domain outcomes.

SituationExample
Protocol failureA request uses an unsupported method
Tool execution failureA stock lookup cannot obtain its record
Valid domain resultAn authorized product has zero units available
Uncertain external outcomeA downstream write times out without a definitive receipt

Zero stock is not an error. A missing record should not be silently converted into zero. A successful protocol response also does not automatically establish that a business action succeeded.

Depending on the failure and applicable specification, an implementation may return a protocol error or a tool result with isError set to true. HTTP authentication failures can be represented at the transport/authorization layer. Avoid exposing raw stack traces, credentials or unnecessary internal details to callers.

A server can also send supported notifications. A list-change notification can tell a client that advertised tools or other capabilities need refreshing. A resource update can inform an appropriately subscribed client that information changed. Progress notifications can report progress for applicable operations using supported protocol mechanisms.

A JSON-RPC notification does not have a request ID and does not receive a JSON-RPC response. A server-initiated request, by contrast, expects a response. Features such as sampling or elicitation require the appropriate negotiated client support and policy.

Do not claim support for notifications merely because a server has an event loop. Advertise only implemented features and emit messages according to their protocol conditions. Later lessons cover notification types, subscriptions, progress and cancellation.

9. Tested implementation: server-side capability dispatch#

The following standard-library Python example isolates the server's domain-facing responsibilities. It registers three kinds of capabilities, exposes a small capability advertisement, filters discovery, dispatches requests by capability type and performs a tenant-scoped stock lookup.

It does not implement JSON-RPC, transport, initialization, real authentication, token validation or an SDK. Its Actor object represents identity and scopes already established by trusted application middleware. The scope names are invented for the exercise and are not standardized MCP scopes. The policy document and prompt template are intentionally shared across authorized actors.

Save as server_demo.py:

PYTHON
from dataclasses import dataclass @dataclass(frozen=True) class Actor: tenant: str scopes: frozenset[str] class InventoryService: def __init__(self): self.rows = {('A', 'A12'): 7, ('A', 'B34'): 0, ('B', 'X99'): 12} def stock(self, tenant, sku): return self.rows[(tenant, sku)] class Server: def __init__(self, service): self.service = service self.tools = {'stock': self.stock} self.resources = {'policy://returns': 'Returns within 30 days.'} self.prompts = {'stock_summary': 'Summarize verified stock for {sku}.'} def capabilities(self): return {kind: {} for kind, registry in ( ('tools', self.tools), ('resources', self.resources), ('prompts', self.prompts)) if registry} def discover(self, kind, actor): registry = {'tools': self.tools, 'resources': self.resources, 'prompts': self.prompts}[kind] return sorted(registry) if kind + ':read' in actor.scopes else [] def dispatch(self, kind, key, args, actor): if kind + ':read' not in actor.scopes: raise PermissionError('Access denied') if kind == 'tools': if key not in self.tools: raise LookupError('Unknown tool') return self.tools[key](args, actor) if kind == 'resources': if args != {}: raise ValueError('Unexpected arguments') return self.resources[key] if kind == 'prompts': sku = self.sku(args) return self.prompts[key].format(sku=sku) raise LookupError('Unknown capability type') @staticmethod def sku(args): if (not isinstance(args, dict) or set(args) != {'sku'} or type(args['sku']) is not str or not 1 <= len(args['sku']) <= 16 or not args['sku'].isascii() or not args['sku'].isalnum()): raise ValueError('Invalid SKU arguments') return args['sku'] def stock(self, args, actor): sku = self.sku(args) try: count = self.service.stock(actor.tenant, sku) except KeyError: return {'isError': True, 'content': [ {'type': 'text', 'text': 'Stock record unavailable'}]} return {'content': [{'type': 'text', 'text': str(count)}]} def reject(fn, expected): try: fn() except expected: return raise AssertionError('Expected rejection') if __name__ == '__main__': server = Server(InventoryService()) a = Actor('A', frozenset({'tools:read', 'resources:read', 'prompts:read'})) denied = Actor('A', frozenset()) assert set(server.capabilities()) == {'tools', 'resources', 'prompts'} assert server.discover('tools', a) == ['stock'] assert server.discover('tools', denied) == [] assert server.dispatch('tools', 'stock', {'sku': 'A12'}, a)['content'][0]['text'] == '7' assert server.dispatch('tools', 'stock', {'sku': 'B34'}, a)['content'][0]['text'] == '0' assert server.dispatch('tools', 'stock', {'sku': 'X99'}, a)['isError'] assert server.dispatch('tools', 'stock', {'sku': 'missing'}, a)['isError'] reject(lambda: server.dispatch('tools', 'stock', {'sku': 'A12'}, denied), PermissionError) reject(lambda: server.dispatch('tools', 'stock', {'sku': 'A12', 'tenant': 'B'}, a), ValueError) reject(lambda: server.dispatch('tools', 'delete', {'sku': 'A12'}, a), LookupError) assert server.dispatch('resources', 'policy://returns', {}, a) == 'Returns within 30 days.' assert server.dispatch('prompts', 'stock_summary', {'sku': 'A12'}, a) == 'Summarize verified stock for A12.' print('12 server capability checks passed')

Run with Python 3.10 or later:

BASH
python -m py_compile server_demo.py python server_demo.py

Actual local output using Python 3.13.5:

12 server capability checks passed

The first three checks verify capability advertisement and discovery filtering. The next four distinguish positive stock, zero stock, another tenant's record and a missing record. Three rejection checks cover insufficient permission, an attempt to inject a tenant argument and an unregistered operation. The final two verify resource and prompt retrieval.

Notice that discovery returns only names in this fixture. A real SDK must return complete protocol descriptors, not just these strings. The example's resource and prompt handlers return raw application data, which a real SDK adapter must encode in the corresponding MCP content and message structures.

The in-memory repository scopes lookups by the trusted actor's tenant. The unavailable-record response deliberately does not distinguish a nonexistent SKU from a record belonging to another tenant. That helps avoid one direct information leak but does not establish comprehensive resistance to timing attacks or other side channels.

Deliberate limitations: The example does not implement full schemas, dynamic registration, notifications, pagination, authentication, per-resource policy for the shared policy document, concurrency, quotas, deadlines or real downstream calls. It assumes an immutable trusted actor and valid capability kind/key types. Its shared read scopes are sufficient only for this tiny fixture, not for write tools or a production permission system. Raw Python exceptions are not protocol responses. A production integration must map them safely using a supported SDK and verify actual client-server interoperability. The local checks demonstrate only the listed fixture behavior.

10. Server lifecycle and operational ownership#

A server must be initialized and made available according to its deployment model. In a local stdio setup, a client may launch the server subprocess and manage its streams. In a remote setup, the server may be an independently operated HTTP service with multiple client sessions.

A typical operational lifecycle includes:

  1. Load trusted configuration and necessary dependencies.
  2. Register supported handlers and prepare their metadata.
  3. Accept connections and initialize according to the supported revision.
  4. Process authorized discovery and operation requests.
  5. Handle supported notifications, errors and connection changes.
  6. Release resources and stop accepting work during shutdown.

Not every deployment requires long-lived application session state. The server must follow the transport and protocol revision it implements, rather than assume that every MCP deployment has identical stateful lifecycle behavior.

Do not equate a running process with a healthy capability. A server can start while its downstream database is unavailable. Monitor handler outcomes, authorization failures, dependency health, request latency and resource usage. Use appropriate health and readiness checks for the deployment.

Shutdown needs to distinguish transport resources from ongoing business operations. Closing a connection may not cancel or reverse a previously committed side effect. Long-running work needs explicit ownership, deadlines and reconciliation according to its application contract.

11. Server design checklist#

AreaDesign question
Capability contractAre the names, schemas, descriptions and behavior consistent?
CompatibilityWhich protocol revisions and transports are supported?
DiscoveryAre only supported and appropriately visible capabilities listed?
AuthorizationIs access checked using trusted identity for the actual operation and resource?
Downstream serviceAre business rules enforced at the authoritative boundary?
Result encodingAre content, errors and business outcomes represented correctly?
LifecycleAre connections, pending work and resources managed appropriately?
SecurityAre credentials isolated, inputs validated and data disclosure minimized?
TestingAre handlers tested separately and through a real compatible client?

Start with one narrow capability that has clear semantics and an identified owner. Add further tools, resources or prompts only when they serve a consumer requirement. Prefer business-oriented interfaces to exposing broad unrestricted operations.

Interview-ready answer#

An MCP server is the component that exposes and implements capabilities through the Model Context Protocol. It can offer tools for callable operations, resources for URI-identified information and prompts for reusable messages. It advertises supported features, handles discovery and requests, dispatches to registered handlers, validates input, enforces authorization, accesses underlying services and returns appropriate results or errors. It may send supported notifications and manage connection-related lifecycle state. Unlike the host, which coordinates the user and optional model, or the client, which handles the consuming side of protocol communication, the server owns the capability implementation and its access boundary. A server does not inherently require an LLM or a remote deployment.

Next lesson: Q21 explores how a host isolates client connections and capabilities across multiple servers, building on the three architectural roles introduced in this module.

References

  1. 1.
  2. 2.
    MCP architecturemodelcontextprotocol.io
  3. 3.
    MCP lifecyclemodelcontextprotocol.io
  4. 4.
    MCP toolsmodelcontextprotocol.io
  5. 5.
    MCP resourcesmodelcontextprotocol.io
  6. 6.
    MCP promptsmodelcontextprotocol.io
  7. 7.
    MCP authorizationmodelcontextprotocol.io
  8. 8.
    MCP transportsmodelcontextprotocol.io
  9. 9.
  10. 10.
    JSON-RPC 2.0jsonrpc.org

Related questions

Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation