================================================================
Files
================================================================
================
File: docs/getting-started/quick-overview.md
================
---
title: Quick Overview
description: An overview of the ContextVM documentation, including the specification and SDK documentation.
---
# Quick Overview
Welcome to the ContextVM documentation! This guide provides a brief overview of what you'll find in our documentation to help you get started with ContextVM.
## Documentation Structure
Our documentation is organized into several main sections:
### 🚀 Getting Started
- **Quick Overview**: This page - a brief introduction to what ContextVM offers
### 📋 Specification
- **[Specification](/spec/ctxvm-draft-spec)**: The official ContextVM draft specification detailing the protocol
- **[CEP - Guidelines](/spec/cep-guidelines)**: ContextVM Enhancement Proposal guidelines for contributing to the protocol
### 🛠️ ts-SDK
The TypeScript SDK provides tools and libraries for building applications with ContextVM:
- **[SDK Quick Overview](/ts-sdk/quick-overview)**: A comprehensive overview of the SDK's modules and core concepts
- **Core Concepts**: Fundamental definitions, constants, interfaces, and utilities
- **Transports**: Communication modules for MCP over Nostr
- **Components**: Gateway, Relay Handlers, Signers, and Proxy implementations
- **Tutorials**: Practical examples and guides
## What is ContextVM?
ContextVM is a protocol that bridges the Model Context Protocol (MCP) with the Nostr network, enabling decentralized communication. It allows MCP servers and clients to communicate over the Nostr protocol, leveraging its decentralized infrastructure for secure and private interactions.
## Key Features
- **Decentralized Communication**: Use Nostr's decentralized network for MCP communication
- **Security First**: Leveraging Nostr's cryptographic primitives for verification, authorization, and additional features
- **Easy Integration**: Typescript SDK to work with ContextVM
## Getting Started
1. **Read the Specification**: Start with the [ContextVM specification](/spec/ctxvm-draft-spec) to understand the protocol
2. **Explore the SDK**: Check out the [SDK Quick Overview](/ts-sdk/quick-overview) for development guidance
3. **Follow Tutorials**: Work through practical examples to see ContextVM in action
## Next Steps
Choose your path based on your interests:
- **Protocol Development**: Dive into the [Specification](/spec/ctxvm-draft-spec) to understand the protocol details
- **SDK Development**: Start with the [SDK Quick Overview](/ts-sdk/quick-overview) to begin building with ContextVM
- **Contributing**: Learn about contributing to the protocol with [CEP Guidelines](/spec/cep-guidelines)
For the latest updates and community discussions, visit our [GitHub repository](https://github.com/contextvm/).
================
File: docs/spec/ceps/cep-4.md
================
---
title: CEP-4 Encryption Support
description: End-to-end encryption for ContextVM messages using NIP-17 and NIP-59
---
# Encryption Support
**Status:** Final
**Author:** @contextvm-org
**Type:** Standards Track
## Abstract
This CEP proposes optional end-to-end encryption for ContextVM messages to enhance privacy and security. The encryption mechanism leverages a simplified version of NIP-17 (Private Direct Messages) for secure message encryption and NIP-59 (Gift Wrap) pattern with no 'rumor' using NIP-59 gift wrapping for metadata protection. This approach ensures message content privacy and metadata protection while maintaining full compatibility with the standard protocol.
## Specification
### Encryption Support Discovery
Encryption support is advertised through the `support_encryption` tag in server initialization responses or public server announcements. The presence of this tag indicates that the server supports encryption; its absence signifies that the server does not support encryption:
```json
{
"pubkey": "<server-pubkey>",
"content": {
/* server details */
},
"tags": [
["support_encryption"] // Presence alone indicates encryption support
// ... other tags
]
}
```
Clients can discover encryption support by:
1. **Direct Discovery**: Check for the presence of the `support_encryption` tag in initialization responses
2. **Encrypted Handshake**: Attempt an encrypted initialization
### Message Encryption Flow
When encryption is enabled, ContextVM messages follow a simplified NIP-17 pattern with no 'rumor', using NIP-59 gift wrapping.
#### 1. Content Preparation
The request is prepared as usual, and should be signed:
```json
{
"kind": 25910,
"id": "<request-event-id>",
"pubkey": "<client-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": {
"location": "New York"
}
}
},
"tags": [["p", "<server-pubkey>"]],
"sig": "<signature>"
}
```
#### 2. Seal Creation
The request is converted into a JSON string and encrypted to the recipient's public key, following NIP-44 encryption scheme.
#### 3. Gift Wrapping
The encrypted request is then gift-wrapped by placing it in the content field of a NIP-59 gift-wrap event.
```json
{
"id": "<gift-wrap-hash>",
"pubkey": "<random-pubkey>",
"created_at": "<randomized-timestamp>",
"kind": 1059,
"tags": [["p", "<server-pubkey>"]],
"content": "<nip44-encrypted-request>",
"sig": "<random-key-signature>"
}
```
Server responses follow the same pattern.
The decrypted inner content contains the standard ContextVM response format. The id field used in responses should match the inner id field used in requests, not the id of the gift-wrap event.
#### Observations
While this encryption scheme is secure and private enough, it has a main limitation in metadata leakage protection, as the recipient's public key is added to the gift-wrap event as a `p` tag. Therefore, the only leaked metadata is the recipient's public key, but not the sender, the kind of event contained in the gift-wrap, or the timestamp of the event. This is a limitation of the NIP-59 gift-wrapping pattern.
## Backward Compatibility
This CEP introduces no breaking changes to the existing protocol. Encryption is entirely optional:
- **Existing servers** continue to work without modification
- **Existing clients** continue to work with existing servers
- **New encrypted communication** only occurs when both client and server support encryption
The only compatibility issue is that servers or clients might require encrypted communication. Therefore, if encryption is required and one of the participants does not support it, the communication will fail
## Reference Implementation
A reference implementation can be found in the [ContextVM sdk](https://github.com/ContextVM/sdk/blob/master/src/core/encryption.ts)
================
File: docs/spec/ceps/cep-6.md
================
---
title: CEP-6 Public Server Announcements
description: Public server discovery mechanism for ContextVM capabilities
---
# Public Server Announcements
**Status:** Final
**Author:** @contextvm-org
**Type:** Standards Track
## Abstract
This CEP proposes a public server discovery mechanism for ContextVM using Nostr replaceable events. The mechanism allows MCP servers to advertise their capabilities and metadata through the Nostr network, enabling clients to discover and browse available services without requiring prior knowledge of server public keys. This enhances discoverability while maintaining the decentralized nature of the protocol.
## Specification
### Overview
Public server announcements act as a service catalog, allowing clients or users to discover servers and their capabilities through replaceable events on the Nostr network. This mechanism provides an initial overview of what a server offers, and their public keys to connect with them.
Since each server is uniquely identified by its public key, the announcement events are replaceable (kinds 11316-11320), ensuring that only the most recent version of the server's information is active.
Providers announce their servers and capabilities by publishing events with kinds 11316 (server), 11317 (tools/list), 11318 (resources/list), 11319 (resource templates/list), and 11320 (prompts/list).
**Note:** The examples below present the `content` as a JSON object for readability; it must be stringified before inclusion in a Nostr event.
### Event Kinds for Server Announcements
| Kind | Description |
| ----- | ----------------------- |
| 11316 | Server Announcement |
| 11317 | Tools List |
| 11318 | Resources List |
| 11319 | Resource Templates List |
| 11320 | Prompts List |
### Server Announcement Event
```json
{
"kind": 11316,
"pubkey": "<provider-pubkey>",
"content": {
"protocolVersion": "2025-07-02",
"capabilities": {
"prompts": {
"listChanged": true
},
"resources": {
"subscribe": true,
"listChanged": true
},
"tools": {
"listChanged": true
}
},
"serverInfo": {
"name": "ExampleServer",
"version": "1.0.0"
},
"instructions": "Optional instructions for the client"
},
"tags": [
["name", "Example Server"], // Optional: Human-readable server name
["about", "Server description"], // Optional: Server description
["picture", "https://example.com/server.png"], // Optional: Server icon/avatar URL
["website", "https://example.com"], // Optional: Server website
["support_encryption"] // Optional: Presence indicates server supports encrypted messages
]
}
```
#### Content Field Structure
The `content` field contains structured server information following the [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization), it should be a JSON string.
#### Tags Field Structure
The `tags` field provides additional metadata for discoverability:
- **name**: Human-readable server name
- **about**: Server description
- **picture**: URL to server icon/avatar
- **website**: Server website URL
- **support_encryption**: Indicates server supports encrypted messages
### Capability List Announcements
As in the Server Announcement event, the `content` field contains a JSON string with the list of capabilities. The list is the result of a call to the `list` method of each capability.
### Tools List Event Example
```json
{
"kind": 11317,
"pubkey": "<provider-pubkey>",
"content": {
"tools": [
{
"name": "get_weather",
"description": "Get current weather information for a location",
"inputSchema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name or zip code"
}
},
"required": ["location"]
}
}
]
},
"tags": []
}
```
### Discovery Process
#### Client Discovery Flow
1. **Subscribe to Server Announcement**: Clients subscribe to kinds 11316 (Server Announcement) on Nostr relays
2. **Subcribe to Capability List Announcements**: Once the server announcement is fetched and parsed, the client can subscribe to the capabilities events present in the server announcement.
3. **Initialize Connection**: Client proceeds with standard MCP initialization using the server's public key
An alternative flow is to subscribe to all announcements published by the server public key, and get all the public announcements at once, instead of first fetching the server announcement and then fetching the capabilities.
### Event Replacement Behavior
Since announcement events use kinds 11316-11320 (in the 10000-20000 range), they are replaceable:
- **Relay Behavior**: Relays store only the latest event for each combination of kind, and pubkey
- **Client Behavior**: Clients should always request the latest version of announcement events
- **Server Behavior**: Servers must update announcement events when capabilities change
## Reference Implementation
A reference implementation can be found in the [ContextVM SDK server transport implementation](https://github.com/ContextVM/sdk/blob/master/src/transport/nostr-server-transport.ts). It is implemented by calling the list methods from the transport during the initialization of the transport and then publishing the results of those list methods.
## Dependencies
- [CEP-4: Encryption Support](/spec/ceps/cep-4)
================
File: docs/spec/ceps/cep-8.md
================
---
title: CEP-8 Capability Pricing and Payment Flow
description: Pricing mechanism and payment processing for ContextVM capabilities
---
# Capability Pricing and Payment Flow
**Status:** Draft
**Author:** @Gzuuus
**Type:** Standards Track
## Abstract
This CEP proposes a standardized pricing mechanism and payment flow for MCP capabilities over ContextVM. The mechanism allows servers to advertise pricing for their capabilities, enables clients to discover and pay for these capabilities through various payment methods, and defines a notification system for payment requests. This creates a sustainable ecosystem for capability servers while maintaining the decentralized nature of the protocol.
## Specification
### Overview
ContextVM pricing for capabilities is implemented through a standardized mechanism with three main components:
1. **Pricing Tags**: Servers advertise pricing information using the `cap` tag
2. **Payment Method Identifiers (PMI)**: Both parties advertise supported payment methods using the `pmi` tag
3. **Payment Notifications**: Servers notify clients of payment requirements through the `notifications/payment_required` notification
When a capability requires payment, the server acts as the payment processor (generating and validating payment requests) while the client acts as the payment handler (executing payments for supported payment methods). Clients can discover supported payment methods beforehand through PMI discovery, enabling informed decisions before initiating requests.
### New Tags Introduced
This CEP introduces two new tags to the ContextVM protocol:
#### `cap` Tag
The `cap` tag is used to convey pricing information for capabilities. It follows this format:
```json
["cap", "<capability-identifier>", "<price>", "<currency-unit>"]
```
Where:
- `<capability-identifier>` is the name of the tool, prompt, or resource URI
- `<price>` is a string representing the numerical amount. For fixed prices, this is an integer (e.g., "100"). For variable prices, this can be a range (e.g., "100-1000") to indicate a variable pricing model.
- `<currency-unit>` is the currency symbol (e.g., "sats", "usd")
#### `pmi` Tag
The `pmi` tag is used to advertise supported Payment Method Identifiers. It follows this format:
```json
["pmi", "<payment-method-identifier>"]
```
Where `<payment-method-identifier>` is a standardized PMI string following the W3C Payment Method Identifiers specification (e.g., "bitcoin-lightning-bolt11", "bitcoin-cashu").
### Pricing Mechanism
Pricing information is advertised using the `cap` tag in server announcements and capability list responses:
#### Server Announcements
```json
{
"kind": 11317,
"content": {
"tools": [
{
"name": "get_weather",
"description": "Get current weather information"
// ... other tool properties
}
]
},
"tags": [["cap", "get_weather", "100", "sats"]]
}
```
#### Capability List Responses
```json
{
"kind": 25910,
"pubkey": "<provider-pubkey>",
"content": {
"result": {
"tools": [
{
"name": "get_weather",
"description": "Get current weather information"
// ... other tool properties
}
],
"nextCursor": "next-page-cursor"
}
},
"tags": [
["e", "<request-event-id>"],
["cap", "get_weather", "100", "sats"]
]
}
```
The `cap` tag indicates that using the `get_weather` tool costs 100 satoshis, allowing clients to display pricing to users.
### Payment Method Identifiers (PMI)
The protocol supports multiple payment methods through Payment Method Identifiers (PMI) that follow the W3C Payment Method Identifiers specification.
#### PMI Format and Registry
PMIs MUST follow the format defined by the [W3C Payment Method Identifiers](https://www.w3.org/TR/payment-method-id/) specification, matching the pattern: `[a-z0-9-]+` (e.g., `bitcoin-onchain`, `bitcoin-lightning-bolt11`, `bitcoin-cashu`, `basic-card`, etc).
**ContextVM PMI References:**
- `"bitcoin-onchain"` - Bitcoin on-chain transactions
- `"bitcoin-lightning-bolt11"` - Lightning Network with BOLT11 invoice format
- `"bitcoin-cashu"` - Bitcoin via Cashu ecash tokens
**Note:** The listed PMIs are reference recommendations for the ContextVM ecosystem. Users can use any PMI that follows the W3C format, propose new PMIs for inclusion, or extend the reference list over time.
#### PMI Benefits and Roles
Using standardized PMIs provides:
1. **Interoperability**: Clear communication about supported payment methods
2. **Extensibility**: Easy addition of new payment methods
3. **Multi-currency support**: Different PMIs handle different currencies and networks
4. **Clear separation of concerns**: Servers focus on payment processing, clients on payment handling
### PMI Discovery
PMI discovery allows clients and servers to determine compatibility with payment methods, similar to encryption support discovery in [CEP-4](/spec/ceps/cep-4).
#### PMI Advertisement
Servers advertise supported PMIs using the `pmi` tag in initialization responses or public announcements:
```json
{
"pubkey": "<server-pubkey>",
"content": {
/* server details */
},
"tags": [
["pmi", "bitcoin-lightning-bolt11"],
["pmi", "bitcoin-cashu"],
["pmi", "bitcoin-onchain"]
]
}
```
Clients advertise their supported PMIs in initialization requests:
```json
{
"kind": 25910,
"content": {
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"protocolVersion": "2025-07-02"
// Other initialization parameters
}
},
"tags": [
["p", "<server-pubkey>"],
["pmi", "bitcoin-lightning-bolt11"],
["pmi", "bitcoin-cashu"]
]
}
```
#### Discovery Methods
Clients can discover PMI support through:
1. **Public Announcements**: Check `pmi` tags in server announcements
2. **Initialization Responses**: Check `pmi` tags in server initialization responses
3. **Stateless Operations**: Handle compatibility at request time when no prior discovery is possible
Servers can discover PMI support through:
1. **Client Initialization Request**: Check `pmi` tags in client initialization request
### Payment Flow
The complete payment flow for a capability with pricing information follows these steps:
#### 1. Capability Request
The client sends a capability request to the server:
```json
{
"kind": 25910,
"id": "<request-event-id>",
"pubkey": "<client-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": {
"location": "New York"
}
}
},
"tags": [["p", "<provider-pubkey>"]]
}
```
#### 2. Payment Required Notification
If the capability requires payment, the server responds with a `notifications/payment_required` notification containing payment details:
```json
{
"kind": 25910,
"pubkey": "<provider-pubkey>",
"content": {
"method": "notifications/payment_required",
"params": {
"amount": 1000,
"pay_req": "lnbc...",
"description": "Payment for tool execution",
"pmi": "bitcoin-lightning-bolt11"
}
},
"tags": [
["p", "<client-pubkey>"],
["e", "<request-event-id>"]
]
}
```
#### 3. Payment Processing
The client processes the payment and the server verifies it. When the client receives a payment request notification, it matches the PMI to determine if it supports the specified payment method. If compatible, the client processes the payment using the appropriate method for that PMI. The server verifies the payment according to the PMI implementation.
#### 4. Capability Access
Once payment is verified, the server processes the capability request and responds with the result:
```json
{
"kind": 25910,
"pubkey": "<provider-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
}
],
"isError": false
}
},
"tags": [["e", "<request-event-id>"]]
}
```
### Payment Request Notification Fields
The `notifications/payment_required` notification `params` object contains:
- `amount` (required): Numeric payment amount
- `pay_req` (required): Payment request data string
- `description` (optional): Human-readable payment description
- `pmi` (required): Payment Method Identifier string
## Backward Compatibility
This CEP introduces no breaking changes to the existing protocol:
- **Existing servers** can continue to operate without pricing
- **Existing clients** continue to work with existing servers
- **New pricing** is additive - capabilities can be free or paid
- **Optional participation**: Both providers and clients can choose to participate in pricing
## Reference Implementation
// TODO
## Dependencies
- [CEP-4: Encryption Support](/spec/ceps/cep-4)
- [CEP-6: Public Server Announcements](/spec/ceps/cep-6)
- [W3C Payment Method Identifiers](https://www.w3.org/TR/payment-method-id/)
================
File: docs/spec/cep-guidelines.md
================
---
title: ContextVM Enhancement Proposal Guidelines
description: Guidelines for proposing changes to the ContextVM protocol
---
# CEP Guidelines
> ContextVM Enhancement Proposal (CEP) guidelines for proposing changes to the ContextVM protocol
## What is a CEP?
CEP stands for ContextVM Enhancement Proposal. A CEP is a design document providing information to the ContextVM community, or describing a new feature for the ContextVM protocol or its processes or environment. The CEP should provide a concise technical specification of the feature and a rationale for the feature.
We intend CEPs to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into ContextVM. The CEP author is responsible for building consensus within the community and documenting dissenting opinions.
Because the CEPs are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal.
## What qualifies a CEP?
The goal is to reserve the CEP process for changes that are substantial enough to require broad community discussion, a formal design document, and a historical record of the decision-making process. A regular GitHub issue or pull request is often more appropriate for smaller, more direct changes.
Consider proposing a CEP if your change involves any of the following:
- **A New Feature or Protocol Change**: Any change that adds, modifies, or removes features in the ContextVM protocol. This includes:
- Adding new event kinds or Nostr integration patterns.
- Changing the syntax or semantics of existing data structures or messages.
- Introducing a new standard for interoperability between different ContextVM-compatible tools.
- Significant changes to how the specification itself is defined, presented, or validated.
- **A Breaking Change**: Any change that is not backwards-compatible.
- **A Change to Governance or Process**: Any proposal that alters the project's decision-making, contribution guidelines (like this document itself).
- **A Complex or Controversial Topic**: If a change is likely to have multiple valid solutions or generate significant debate, the CEP process provides the necessary framework to explore alternatives, document the rationale, and build community consensus before implementation begins.
## CEP Types
There are three kinds of CEP:
1. **Standards Track** CEP describes a new feature or implementation for the ContextVM protocol. Standards Track CEPs are maintained as separate documents from the main ContextVM specification and extend or enhance the base protocol. The main specification maintains references to all accepted and finalized Standards Track CEPs.
2. **Informational** CEP describes a ContextVM protocol design issue, or provides general guidelines or information to the ContextVM community, but does not propose a new feature. Informational CEPs do not necessarily represent a ContextVM community consensus or recommendation.
3. **Process** CEP describes a process surrounding ContextVM, or proposes a change to (or an event in) a process. Process CEPs are like Standards Track CEPs but apply to areas other than the ContextVM protocol itself.
## Submitting a CEP
The CEP process begins with a new idea for the ContextVM protocol. It is highly recommended that a single CEP contain a single key proposal or new idea. Small enhancements or patches often don't need a CEP and can be injected into the ContextVM development workflow with a pull request to the ContextVM repo. The more focused the CEP, the more successful it tends to be.
Each CEP must have an **CEP author** -- someone who writes the CEP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The CEP author should first attempt to ascertain whether the idea is CEP-able. Posting to the ContextVM community forums (Nostr, Signal, GitHub Discussions) is the best way to go about this.
**Important Note**: The CEP process uses both GitHub Issues and Pull Requests:
- **GitHub Issues** are used for discussion, review, and tracking the CEP proposal lifecycle
- **Pull Requests** are normally used for Standards Track CEPs to contain the actual CEP document and specification changes
### CEP Workflow
CEPs should be submitted as a GitHub Issue in the [ContextVM-docs repository](https://github.com/ContextVM/contextvm-docs). The standard CEP workflow varies slightly depending on the CEP type:
#### For Standards Track CEPs
1. You, the CEP author, create a [well-formatted](#cep-format) GitHub Issue with the `CEP` and `proposal` tags. The CEP number is the same as the GitHub Issue number, the two can be used interchangeably.
2. **Simultaneously**, create a Pull Request that adds a markdown document draft in the `ceps` directory. This PR should contain the focused specification sections following the [CEP Format](#cep-format) structure. Link to this PR in your GitHub Issue.
**Important**: The GitHub Issue and Pull Request serve different purposes and contain different content:
- **GitHub Issue**: Initially contains the comprehensive CEP proposal including all sections (abstract, motivation, rationale, specification, security implications, etc.). This is where community discussion happens. Once a Pull Request is opened, the specification section in the issue should be replaced with a link to the PR to avoid redundancy.
- **Pull Request**: Contains only the specification-related sections (abstract, specification, backwards compatibility, reference implementation, and dependencies) that will become part of the final specification document. The PR should focus exclusively on technical specification content.
3. Find a Maintainer to sponsor your proposal. Maintainers will regularly go over the list of open proposals to determine which proposals to sponsor. You can tag relevant maintainers in your proposal.
4. Once a sponsor is found, the GitHub Issue is assigned to the sponsor. The sponsor will add the `draft` tag.
5. The sponsor will informally review both the Issue and the Pull Request, and may request changes based on community feedback. When ready for formal review, the sponsor will add the `in-review` tag.
6. After the `in-review` tag is added, the CEP enters formal review by the Maintainers. The CEP may be accepted, rejected, or returned for revision.
7. If the CEP has not found a sponsor within three months, Maintainers may close the CEP as `dormant`.
#### For Informational and Process CEPs
1. You, the CEP author, create a [well-formatted](#cep-format) GitHub Issue with the `CEP` and `proposal` tags. The CEP number is the same as the GitHub Issue number, the two can be used interchangeably.
2. Find a Maintainer to sponsor your proposal. Maintainers will regularly go over the list of open proposals to determine which proposals to sponsor. You can tag relevant maintainers in your proposal.
3. Once a sponsor is found, the GitHub Issue is assigned to the sponsor. The sponsor will add the `draft` tag, ensure the CEP number is in the title, and assign a milestone.
4. The sponsor will informally review the proposal and may request changes based on community feedback. When ready for formal review, the sponsor will add the `in-review` tag.
5. After the `in-review` tag is added, the CEP enters formal review by the Maintainers. The CEP may be accepted, rejected, or returned for revision.
6. If the CEP has not found a sponsor within three months, Maintainers may close the CEP as `dormant`.
### CEP Format
Each CEP should have the following parts. For Standards Track CEPs, these sections are distributed between the GitHub Issue and Pull Request as described below:
#### GitHub Issue Content (for discussion and review):
1. **Preamble** -- A short descriptive title, the names and contact info for each author, the current status.
2. **Abstract** -- A short (~200 word) description of the technical issue being addressed.
3. **Motivation** -- The motivation should clearly explain why the existing protocol specification is inadequate to address the problem that the CEP solves. The motivation is critical for CEPs that want to change the ContextVM protocol. CEP submissions without sufficient motivation may be rejected outright.
4. **Rationale** -- The rationale explains why particular design decisions were made. It should describe alternate designs that were considered and related work. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion.
5. **Security Implications** -- If there are security concerns in relation to the CEP, those concerns should be explicitly written out to make sure reviewers of the CEP are aware of them.
6. **Specification** -- Initially, this section should contain the technical specification describing syntax and semantics of any new protocol feature. Once a Pull Request is opened, this section should be replaced with a link to the PR to avoid duplication.
#### Pull Request Content (for specification - Standards Track CEPs only):
1. **Preamble** -- A short descriptive title, the names and contact info for each author, the current status.
2. **Abstract** - A short (~200 word) description of the technical issue being addressed (can reference the Issue for full details)
3. **Specification** - The technical specification should describe the syntax and semantics of any new protocol feature. The specification should be detailed enough to allow competing, interoperable implementations. For Standards Track CEPs, this should include the actual changes to the specification files in the Pull Request.
4. **Backward Compatibility** - All CEPs that introduce backward incompatibilities must include a section describing these incompatibilities and their severity. The CEP must explain how the author proposes to deal with these incompatibilities.
5. **Dependencies** - For Standards Track CEPs, this section should list any CEPs that this proposal depends on. Each dependency should be listed with its CEP number and a brief description of how it relates to the current proposal. This helps maintain a clear dependency map and ensures proper implementation order.
6. **Reference Implementation** - The reference implementation must be completed before any CEP is given status "Final", but it need not be completed before the CEP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of "rough consensus and running code" is still useful when it comes to resolving many discussions of protocol details.
**Important**: Once a Pull Request is open, the GitHub Issue's "Specification" section should be updated to simply link to the PR. This ensures the technical specification is maintained in a single location (the PR) while keeping the issue focused on discussion and consensus building.
### Main Specification Integration
Once a Standards Track CEP reaches "Accepted" status, it should be referenced in the main ContextVM specification document. When a CEP reaches "Final" status, the main specification should be updated to include a link to the finalized CEP document.
This ensures that the main specification maintains an up-to-date record of all protocol extensions and enhancements.
### CEP States
CEPs can be one one of the following states:
- `proposal`: CEP proposal without a sponsor.
- `draft`: CEP proposal with a sponsor.
- `in-review`: CEP proposal ready for review.
- `accepted`: CEP accepted by Maintainers, but still requires final wording and reference implementation.
- `rejected`: CEP rejected by Maintainers.
- `withdrawn`: CEP withdrawn.
- `final`: CEP finalized.
- `superseded`: CEP has been replaced by a newer CEP.
- `dormant`: CEP that has not found sponsors and was subsequently closed.
### CEP Review & Resolution
CEPs are reviewed by the ContextVM Maintainers on a regular basis.
For a CEP to be accepted it must meet certain minimum criteria:
- A prototype implementation demonstrating the proposal
- Clear benefit to the ContextVM ecosystem
- Community support and consensus
Once a CEP has been accepted, the reference implementation must be completed. When the reference implementation is complete and incorporated into the main source code repository, the status will be changed to "Final".
A CEP can also be "Rejected" or "Withdrawn". A CEP that is "Withdrawn" may be re-submitted at a later date.
## Reporting CEP Bugs, or Submitting CEP Updates
How you report a bug, or submit a CEP update depends on several factors, such as the maturity of the CEP, the preferences of the CEP author, and the nature of your comments. For CEPs not yet reaching `final` state, it's probably best to send your comments and changes directly to the CEP author. Once CEP is finalized, you may want to submit corrections as a GitHub comment on the issue or pull request to the reference implementation.
## Transferring CEP Ownership
It occasionally becomes necessary to transfer ownership of CEPs to a new CEP author. In general, we'd like to retain the original author as a co-author of the transferred CEP, but that's really up to the original author. A good reason to transfer ownership is when the original author no longer has the time or interest in updating it or following through with the CEP process, or has become unreachable (not responding to email). A bad reason to transfer ownership is when you don't agree with the direction of the CEP. We try to build consensus around a CEP, but if that's not possible, you can always submit a competing CEP.
================
File: docs/spec/ctxvm-draft-spec.md
================
---
title: ContextVM Protocol Specification
description: Technical specification for the ContextVM protocol
---
**Status:** Draft
## Abstract
The Context Vending Machine (ContextVM) specification defines how the Nostr protocol can be used as a transport layer for the Model Context Protocol (MCP), leveraging the Nostr relay network as the underlying communication mechanism. Also benefiting from Nostr's cryptographic primitives for verification, authorization, and additional features.
## Table of Contents
- [Introduction](#introduction)
- [ContextVM as MCP Transport](#contextvm-as-mcp-transport)
- [Public Key Cryptography](#public-key-cryptography)
- [Protocol Overview](#protocol-overview)
- [Main Actors](#main-actors)
- [Transport Layer Architecture](#transport-layer-architecture)
- [Message Structure](#message-structure)
- [Event Kinds](#event-kinds)
- [Server Discovery](#server-discovery)
- [Client Initialization Request](#client-initialization-request)
- [Server Initialization Response](#server-initialization-response)
- [Client Initialized Notification](#client-initialized-notification)
- [Capability Operations](#capability-operations)
- [List Operations](#list-operations)
- [List Request Template](#list-request-template)
- [List Response Template](#list-response-template)
- [Capability-Specific Item Examples](#capability-specific-item-examples)
- [Call Tool Request](#call-tool-request)
- [Call Tool Response](#call-tool-response)
- [Notifications](#notifications)
- [ContextVM Enhancement Proposals (CEPs)](#contextvm-enhancement-proposals-ceps)
- [Complete Protocol Flow](#complete-protocol-flow)
## Introduction
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) defines a standardized way for servers to expose capabilities and for clients to consume them. MCP is transport-agnostic, meaning it can operate over various communication channels. The Context Vending Machine (ContextVM) specification defines a Nostr-based transport layer for MCP, and some conventions on top for enabling secure, decentralized communication between MCP servers and clients.
### ContextVM as MCP Transport
ContextVM operates at the **transport layer** of MCP, providing a Nostr-based implementation that:
- **Transports MCP messages** through Nostr's relay network
- **Preserves JSON-RPC semantics** while leveraging Nostr's event structure
- **Adds cryptographic verification** and metadata capabilities to standard MCP communication
- **Enables decentralized service discovery** and communication without centralized infrastructure
This approach allows MCP servers and clients to communicate through Nostr while maintaining full compatibility with the MCP specification and gaining the benefits of Nostr's cryptographic security model.
### Public Key Cryptography
ContextVM leverages Nostr's public key cryptography to ensure message authenticity and integrity:
1. **Message Verification**: Every message is cryptographically signed by the sender's private key and can be verified using their public key, ensuring that:
- Server announcements are legitimate
- Client requests are from authorized users
- Responses are from the expected servers
2. **Identity Management**: Public keys serve as persistent identifiers for all actors in the system:
- Servers can maintain consistent identities across relays
- Clients can be uniquely identified for authorization purposes
The cryptographic properties enable secure authorization flows for capability execution without requiring centralized authentication services.
## Protocol Overview
### Transport Layer Architecture
ContextVM operates as a transport layer for MCP, meaning it handles the communication channel while preserving the semantics of MCP messages. The architecture consists of:
1. **Transport Layer**: Nostr events and relays serve as the transport mechanism
2. **Message Layer**: JSON-RPC MCP messages are embedded within Nostr event content
3. **Metadata Layer**: Nostr event tags provide addressing and correlation information
This layered approach allows ContextVM to:
- Transport standard MCP messages without modification
- Add Nostr-specific addressing and verification
- Maintain compatibility with existing MCP implementations
### Message Structure
The protocol uses these key design principles for message handling:
1. **Content Field Structure**: The `content` field of Nostr events contains stringified MCP messages. All MCP message structures are preserved exactly as defined in the MCP specification, ensuring compatibility with standard MCP clients and servers.
2. **Nostr Metadata in Tags**: All Nostr-specific metadata uses event tags:
- `p`: Public key for addressing servers or clients
- `e`: Event ID references for correlating requests and responses
3. **Unified Event Kind**: ContextVM uses a single event kind for all communication:
- `25910`: All ContextVM messages (ephemeral events)
The event kind follows Nostr's conventions in [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md#kinds):
- For kind n such that 20000 <= n < 30000, events are ephemeral, which means they are not expected to be stored by relays for a long period, but rather just transmitted.
### Main Actors
There are three main actors in ContextVM architecture:
- **Servers**: MCP servers exposing capabilities, using a public key to sign messages
- **Relays**: Core component of the Nostr protocol that enables communication between clients and servers
- **Clients**: MCP or Nostr clients that discover and consume capabilities from servers, using a public key to sign messages
## Server Discovery
You can connect to MCP servers using ContextVM by knowing their public key and the relay(s) they are listening on. This process follows the standard MCP initialization specification, with ContextVM providing the transport mechanism by embedding JSON-RPC MCP messages in the `content` field of Nostr events.
**Note:** The content field of ContextVM events contains stringified MCP messages. The examples below present the content as a JSON object for readability; it must be stringified before inclusion in a Nostr event.
#### Client Initialization Request
```json
{
"kind": 25910,
"content": {
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"protocolVersion": "2025-07-02",
"capabilities": {
"roots": {
"listChanged": true
},
"sampling": {}
},
"clientInfo": {
"name": "ExampleClient",
"version": "1.0.0"
}
}
},
"tags": [["p", "<server-pubkey>"]]
}
```
- Tags:
- `p`: Server public key
#### Server Initialization Response
```json
{
"kind": 25910,
"pubkey": "<server-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 0,
"result": {
"protocolVersion": "2025-07-02",
"capabilities": {
"logging": {},
"prompts": {
"listChanged": true
},
"resources": {
"subscribe": true,
"listChanged": true
},
"tools": {
"listChanged": true
}
},
"serverInfo": {
"name": "ExampleServer",
"version": "1.0.0"
},
"instructions": "Optional instructions for the client"
}
},
"tags": [["e", "<client-init-request-id>"]]
}
```
- Tags:
- `e`: Reference to the client's initialization request event
#### Client Initialized Notification
After receiving the server initialization response, the client MUST send an initialized notification to indicate it is ready to begin normal operations:
```json
{
"kind": 25910,
"pubkey": "<client-pubkey>",
"content": {
"jsonrpc": "2.0",
"method": "notifications/initialized"
},
"tags": [
["p", "<provider-pubkey>"] // Required: Target provider public key
]
}
```
This notification completes the initialization process and signals to the server that the client has processed the server's capabilities and is ready to begin normal operations.
**Note:** The initialization process is not required for ContextVM servers to operate as they can work in a stateless fashion. However, it is recommended to use it to ensure that the server is ready to accept requests from clients.
## Capability Operations
After initialization, clients can interact with server capabilities.
### List Operations
All list operations follow the same structure described by MCP, with the specific capability type indicated in the method name.
- Tags:
- `p`: Provider public key
#### List Request Template
```json
{
"kind": 25910,
"pubkey": "<client-pubkey>",
"id": "<request-event-id>",
"content": {
"jsonrpc": "2.0",
"id": 1,
"method": "<capability>/list", // tools/list, resources/list, or prompts/list
"params": {
"cursor": "optional-cursor-value"
}
},
"tags": [
["p", "<provider-pubkey>"] // Required: Provider's public key
]
}
```
#### List Response Template
```json
{
"kind": 25910,
"pubkey": "<provider-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 1,
"result": {
"<items>": [
// "tools", "resources", or "prompts" based on capability
// Capability-specific item objects
],
"nextCursor": "next-page-cursor"
}
},
"tags": [
["e", "<request-event-id>"] // Required: Reference to the request event
]
}
```
### Capability-Specific Item Examples
#### Call Tool Request
```json
{
"kind": 25910,
"id": "<request-event-id>",
"pubkey": "<client-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": {
"location": "New York"
}
}
},
"tags": [["p", "<provider-pubkey>"]]
}
```
#### Call Tool Response
```json
{
"kind": 25910,
"pubkey": "<provider-pubkey>",
"content": {
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
}
],
"isError": false
}
},
"tags": [["e", "<request-event-id>"]]
}
```
For other capabilities (resources, prompts, completions, ping, etc.), the `content` field follows the same pattern as other MCP messages, containing a stringified JSON-RPC object that adheres to the MCP specification.
## Notifications
All notifications in ContextVM follow the standard MCP notification format and conventions, using the unified kind 25910 event type. This includes notifications for payment requests, progress updates, and all other server-to-client or client-to-server communications.
Notifications are constructed according to the standard MCP notification template.
## ContextVM Enhancement Proposals (CEPs)
The ContextVM protocol is subject to ongoing improvements and enhancements. These improvements are managed through the ContextVM Enhancement Proposal (CEP) process, which is described in detail in the [CEP Guidelines](https://docs.contextvm.org/spec/cep-guidelines/)
### Accepted CEPs
The following CEPs have been accepted:
### Final CEPs
The following CEPs have been finalized:
- [CEP-4: Encryption Support](/spec/ceps/cep-4)
- [CEP-6: Public Server Announcements](/spec/ceps/cep-6)
## Complete Protocol Flow
```mermaid
sequenceDiagram
participant MCP Client
participant Relays
participant MCP Server
note over MCP Client, MCP Server: MCP Initialization over Relays
MCP Client->>Relays: Publish kind 25910 (initialize request)
Relays->>MCP Server: Deliver MCP initialize message
MCP Server->>Relays: Publish kind 25910 (initialize response)
Relays-->>MCP Client: Deliver MCP initialize response
MCP Client->>Relays: Publish kind 25910 (initialized notification)
Relays->>MCP Server: Deliver MCP initialized notification
note over MCP Client, MCP Server: MCP Capability Operations over Relays
MCP Client->>Relays: Publish kind 25910 (tools/list request)
Relays->>MCP Server: Deliver MCP tools/list request
MCP Server->>Relays: Publish kind 25910 (tools/list response)
Relays-->>MCP Client: Deliver MCP tools/list response
```
================
File: docs/ts-sdk/core/constants.md
================
---
title: Constants
description: A set of constants used throughout the @contextvm/sdk.
---
# Constants
The `@contextvm/sdk` exports a set of constants that are used throughout the library for event kinds, tags, and other protocol-specific values. These constants ensure consistency and alignment with the ContextVM specification.
## Event Kinds
The ContextVM protocol defines several Nostr event kinds for different types of messages.
| Constant | Kind | Description |
| ----------------------------- | ----- | ----------------------------------------------------------------------------- |
| `CTXVM_MESSAGES_KIND` | 25910 | The kind for standard, ephemeral ContextVM messages. |
| `GIFT_WRAP_KIND` | 1059 | The kind for encrypted messages, wrapped using the NIP-59 gift wrap standard. |
| `SERVER_ANNOUNCEMENT_KIND` | 11316 | A replaceable event for announcing a server's presence and basic info. |
| `TOOLS_LIST_KIND` | 11317 | A replaceable event for listing a server's available tools. |
| `RESOURCES_LIST_KIND` | 11318 | A replaceable event for listing a server's available resources. |
| `RESOURCETEMPLATES_LIST_KIND` | 11319 | A replaceable event for listing a server's available resource templates. |
| `PROMPTS_LIST_KIND` | 11320 | A replaceable event for listing a server's available prompts. |
## Nostr Tags
The SDK defines an object `NOSTR_TAGS` that contains constants for the various Nostr event tags used in the ContextVM protocol.
| Key | Tag | Description |
| -------------------- | -------------------- | ---------------------------------------------------------------------- |
| `PUBKEY` | `p` | The public key of the message recipient. |
| `EVENT_ID` | `e` | The event ID used to correlate requests and responses. |
| `CAPABILITY` | `cap` | A tag for specifying pricing metadata for a tool, resource, or prompt. |
| `NAME` | `name` | The human-readable name of a server in an announcement. |
| `WEBSITE` | `website` | The URL of a server's website in an announcement. |
| `PICTURE` | `picture` | The URL of a server's icon in an announcement. |
| `ABOUT` | `about` | A tag for providing a short description of a server. |
| `SUPPORT_ENCRYPTION` | `support_encryption` | A tag indicating that a server supports end-to-end encryption. |
## Announcement Methods
The `announcementMethods` object maps capability types to their corresponding MCP method names for server announcements.
```typescript
export const announcementMethods = {
server: "initialize",
tools: "tools/list",
resources: "resources/list",
resourceTemplates: "resources/templates/list",
prompts: "prompts/list",
} as const;
```
This object is used internally by the `NostrServerTransport` to construct announcement events.
## Next Steps
With a solid understanding of the core modules, you are now ready to explore the **[Transports](/transports/base-nostr-transport)**, which are responsible for all network communication in the SDK.
================
File: docs/ts-sdk/core/encryption.md
================
---
title: Encryption
description: An overview of the encryption mechanism in the @contextvm/sdk.
---
# Encryption
The `@contextvm/sdk` supports optional end-to-end encryption for all communication, providing enhanced privacy and security. This section explains the encryption mechanism, how to enable it, and the underlying principles.
## Overview
ContextVM's encryption leverages a simplified version of [NIP-17](https://github.com/nostr-protocol/nips/blob/master/17.md) to ensure:
1. **Message Content Privacy**: All MCP message content is encrypted using NIP-44.
2. **Metadata Protection**: The gift wrap pattern conceals participant identities and other metadata.
3. **Selective Encryption**: Clients and servers can negotiate encryption on a per-session basis.
When encryption is enabled, all ephemeral messages (kind 25910) are wrapped in a kind 1059 gift wrap event. Server announcements and capability lists remain unencrypted for public discoverability.
## How It Works
The encryption flow is designed to be secure and efficient:
1. **Content Preparation**: The original MCP message is serialized into a standard Nostr event.
2. **Gift Wrapping**: The entire event is then encrypted using `nip44.v2` and wrapped inside a "gift wrap" event (kind 1059). A new, random keypair is generated for each gift wrap.
3. **Transmission**: The encrypted gift wrap event is published to the Nostr network.
The recipient then unwraps the gift using their private key to decrypt the original message.
### Why a Simplified NIP-17/NIP-59 Pattern?
The standard implementation of NIP-17 is designed for persistent private messages and includes a "rumor" and "seal" mechanism to prevent message leakage. Since ContextVM messages are ephemeral and not intended to be stored by relays, this complexity is unnecessary. The SDK uses a more direct gift-wrapping approach that provides strong encryption and metadata protection without the overhead of the full NIP-17 standard.
## Enabling Encryption
Encryption is configured at the transport level using the `EncryptionMode` enum. You can set the desired mode when creating a `NostrClientTransport` or `NostrServerTransport`.
```typescript
import { NostrClientTransport } from "@contextvm/sdk";
import { EncryptionMode } from "@contextvm/sdk";
const transport = new NostrClientTransport({
// ... other options
encryptionMode: EncryptionMode.OPTIONAL, // or REQUIRED, DISABLED
});
```
### `EncryptionMode`
- **`REQUIRED`**: The transport will only communicate with peers that support encryption. If the other party does not support it, the connection will fail.
- **`OPTIONAL`**: (Default) The transport will attempt to use encryption if the peer supports it. If not, it will fall back to unencrypted communication.
- **`DISABLED`**: The transport will not use encryption, even if the peer supports it.
## Encryption Support Discovery
Clients and servers can discover if a peer supports encryption in two ways:
1. **Server Announcements**: Public server announcements (kind 11316) include a `support_encryption` tag to indicate that the server is capable of encrypted communication.
2. **Initialization Handshake**: During the MCP initialization process, both the client and server can signal their support for encryption.
## API Reference
The core encryption functions are exposed in the `core` module:
- `encryptMessage(message: string, recipientPublicKey: string): NostrEvent`
- `decryptMessage(event: NostrEvent, signer: NostrSigner): Promise<string>`
These functions handle the low-level details of gift wrapping and unwrapping, but in most cases, you will interact with encryption through the transport's `encryptionMode` setting.
## Next Steps
Now that you understand how encryption works, let's look at the [Constants](/core/constants) used throughout the SDK.
================
File: docs/ts-sdk/core/interfaces.md
================
---
title: Interfaces
description: A deep dive into the core interfaces used in the @contextvm/sdk.
---
# Core Interfaces
The `@contextvm/sdk` is designed with a modular and extensible architecture, centered around a set of core interfaces. These interfaces define the essential components for signing, relay management, and communication.
## `NostrSigner`
The `NostrSigner` interface is fundamental for cryptographic operations within the SDK. It abstracts the logic for signing Nostr events, ensuring that all communications are authenticated and verifiable.
### Definition
```typescript
export interface NostrSigner {
getPublicKey(): Promise<string>;
signEvent(event: EventTemplate): Promise<NostrEvent>;
// Optional NIP-04 encryption support (deprecated)
nip04?: {
encrypt: (pubkey: string, plaintext: string) => Promise<string>;
decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
};
// Optional NIP-44 encryption support
nip44?: {
encrypt: (pubkey: string, plaintext: string) => Promise<string>;
decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
};
}
```
Any object that implements this interface can be used to sign events, allowing you to integrate with various key management systems, such as web, hardware wallets or remote signing services. The SDK provides a default implementation, `PrivateKeySigner`, which signs events using a raw private key.
- **Learn more:** [`NostrSigner` Deep Dive](/signer/nostr-signer-interface/)
- **Default Implementation:** [`PrivateKeySigner`](/signer/private-key-signer/)
## `RelayHandler`
The `RelayHandler` interface manages interactions with Nostr relays. It is responsible for subscribing to events and publishing events to the Nostr network.
### Definition
```typescript
export interface RelayHandler {
connect(): Promise<void>;
disconnect(relayUrls?: string[]): Promise<void>;
publish(event: NostrEvent): Promise<void>;
subscribe(
filters: Filter[],
onEvent: (event: NostrEvent) => void,
onEose?: () => void,
): Promise<void>;
unsubscribe(): void;
}
```
By implementing this interface, you can create custom relay management logic, such as sophisticated relay selection strategies or custom reconnection policies. The SDK includes `SimpleRelayPool` as a default implementation.
- **Learn more:** [`RelayHandler` Deep Dive](/relay/relay-handler-interface)
- **Default Implementation:** [`SimpleRelayPool`](/relay/simple-relay-pool)
## `EncryptionMode`
The `EncryptionMode` enum defines the encryption policy for a transport.
```typescript
export enum EncryptionMode {
OPTIONAL = "optional",
REQUIRED = "required",
DISABLED = "disabled",
}
```
This enum is used to configure the encryption behavior of the `NostrClientTransport` and `NostrServerTransport`.
- **Learn more:** [Encryption](/core/encryption)
## `ServerInfo`
The `ServerInfo` interface provides metadata about a server, used by the Nostr server transport to add metadata to server announcements.
### Definition
```typescript
export interface ServerInfo {
name?: string;
picture?: string;
website?: string;
about?: string;
}
```
This interface allows servers to include descriptive information in their announcements, making them more discoverable and providing users with context about the server's purpose and identity.
- **name**: A human-readable name for the server
- **picture**: URL to an image representing the server
- **website**: The server's official website or repository
- **about**: A description of the server's purpose or content
================
File: docs/ts-sdk/core/logging.md
================
---
title: Logging
description: Logging in the @contextvm/sdk
---
### Logging
The SDK uses Pino for high-performance logging with structured JSON output. By default, logs are written to stderr to comply with the MCP protocol expectations.
#### Basic Usage
[`typescript`](src/content/docs/ts-sdk/core/logging.md:10)
```typescript
import { createLogger } from "@contextvm/sdk/core";
// Create a logger for your module
const logger = createLogger("my-module");
logger.info("Application started");
logger.error("An error occurred", { error: "details" });
```
#### Configuration Options
[`typescript`](src/content/docs/ts-sdk/core/logging.md:20)
```typescript
import { createLogger, LoggerConfig } from "@contextvm/sdk/core";
const config: LoggerConfig = {
level: "debug", // Minimum log level (debug, info, warn, error)
file: "app.log", // Optional: log to a file instead of stderr
};
const logger = createLogger("my-module", config);
```
**Note:** Pretty printing is automatically enabled when logs are written to stderr/stdout (not to a file) for better readability during development.
#### Configuring with Environment Variables
The logger can be configured using environment variables, which is useful for adjusting log output without changing the code.
- **`LOG_LEVEL`**: Sets the minimum log level.
- **Values**: `debug`, `info`, `warn`, `error`.
- **Default**: `info`.
- **`LOG_DESTINATION`**: Sets the log output destination.
- **Values**: `stderr` (default), `stdout`, or `file`.
- **`LOG_FILE`**: Specifies the file path when `LOG_DESTINATION` is `file`.
- **`LOG_ENABLED`**: Enables or disables logging.
- **Values**: `true` (default) or `false`.
##### Configuration in Node.js
[`bash`](src/content/docs/ts-sdk/core/logging.md:49)
```bash
# Set log level to debug
LOG_LEVEL=debug node app.js
# Log to a file instead of the console
LOG_DESTINATION=file LOG_FILE=./app.log node app.js
# Disable logging entirely
LOG_ENABLED=false node app.js
```
##### Configuration in Browsers
[`javascript`](src/content/docs/ts-sdk/core/logging.md:63)
```javascript
// Set this in a <script> tag in your HTML or at the top of your entry point
window.LOG_LEVEL = "debug";
// Now, when you import and use the SDK, it will use the 'debug' log level.
import { logger } from "@contextvm/sdk";
logger.debug("This is a debug message.");
```
#### Module-specific Loggers
[`typescript`](src/content/docs/ts-sdk/core/logging.md:75)
```typescript
const baseLogger = createLogger("my-app");
const authLogger = baseLogger.withModule("auth");
const dbLogger = baseLogger.withModule("database");
authLogger.info("User login attempt");
dbLogger.debug("Query executed", { query: "SELECT * FROM users" });
```
#### Conventions and Best Practices
- Log levels:
- debug: detailed developer-oriented information (traces, SQL queries, internal state).
- info: high-level lifecycle events and successful operations (startup, shutdown, user actions).
- warn: unexpected situations that don't stop execution but may need attention.
- error: failures that require investigation (exceptions, failed requests).
- Use structured fields to add context instead of human-parsed messages. Preferred field names:
- `module`: module or component name (string).
- `event`: short event name (string).
- `txId` / `traceId`: request or trace identifier (string).
- `userId`: authenticated user id when applicable (string).
- `durationMs`: operation duration in milliseconds (number).
- `error`: when logging errors, include an `error` object with `message` and `stack`.
- Avoid logging sensitive data (passwords, secrets, full tokens). Redact or hash when necessary.
- Keep log messages concise and use structured metadata for details.
- Prefer logger.method(message, meta) over string interpolation that embeds structured data into the message.
#### Examples (Best Practice)
[`typescript`](src/content/docs/ts-sdk/core/logging.md:105)
```typescript
logger.info("payment.processed", {
module: "payments",
txId: "abcd-1234",
userId: "user-42",
amount: 1999,
currency: "EUR",
durationMs: 245,
});
try {
// do something that throws
} catch (err) {
logger.error("payment.failed", {
module: "payments",
txId: "abcd-1234",
error: { message: err.message, stack: err.stack },
});
}
```
#### Performance and Safety
- The SDK logger is optimized for minimal allocations. Prefer structured objects over building large strings.
- When logging high-frequency events, consider using lower log levels (info -> debug) or sampling.
- Ensure log files are rotated and monitored if using file destinations.
---
See also: [`src/content/docs/ts-sdk/core/interfaces.md`](src/content/docs/ts-sdk/core/interfaces.md:1)
================
File: docs/ts-sdk/gateway/overview.md
================
---
title: Gateway Overview
description: Understanding the NostrMCPGateway component for bridging MCP and Nostr
---
# Gateway
The `NostrMCPGateway` is a server-side bridging component that exposes a traditional MCP server to the Nostr network. It acts as a gateway, translating communication between Nostr-based clients and a standard MCP server.
## Purpose and Capabilities
The gateway manages two transports simultaneously:
1. **Nostr Server Transport**: A [`NostrServerTransport`](/transports/nostr-server-transport) that listens for incoming connections from clients on the Nostr network.
2. **MCP Server Transport**: A standard MCP client transport (like `StdioClientTransport`) that connects to a local or remote MCP server.
The gateway's role is to forward requests from Nostr clients to the MCP server and relay the server's responses back to the appropriate client on Nostr.
## Integration Scenarios
The `NostrMCPGateway` is ideal for:
- **Exposing Existing Servers**: If you have an existing MCP server, you can use the gateway to make it accessible to Nostr clients without modifying the server's core logic. The server continues to operate with its standard transport, while the gateway handles all Nostr-related communication.
- **Decoupling Services**: You can run your core MCP server in a secure environment and use the gateway as a public-facing entry point on the Nostr network. The gateway can be configured with its own security policies (like `allowedPublicKeys`).
- **Adding Nostr Capabilities**: It allows you to add features like public server announcements and decentralized discovery to a conventional MCP server.
## `NostrMCPGatewayOptions`
To create a `NostrMCPGateway`, you need to provide a configuration object that implements the `NostrMCPGatewayOptions` interface:
```typescript
export interface NostrMCPGatewayOptions {
mcpClientTransport: Transport;
nostrTransportOptions: NostrServerTransportOptions;
}
```
- **`mcpClientTransport`**: An instance of a client-side MCP transport that the gateway will use to connect to your existing MCP server. For example, `new StdioClientTransport(...)`.
- **`nostrTransportOptions`**: The full configuration object required by the `NostrServerTransport`. This includes the `signer`, `relayHandler`, and options like `isPublicServer`.
## Usage Example
This example shows how to create a gateway that connects to a local MCP server (running in a separate process) and exposes it to the Nostr network.
```typescript
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { NostrMCPGateway } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
// 1. Configure the signer and relay handler for the Nostr transport
const signer = new PrivateKeySigner("your-gateway-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);
// 2. Configure the transport to connect to your existing MCP server
const clientTransport = new StdioClientTransport({
command: "bun",
args: ["run", "path/to/your/mcp-server.ts"],
});
// 3. Create the gateway instance
const gateway = new NostrMCPGateway({
mcpClientTransport: clientTransport,
nostrTransportOptions: {
signer,
relayHandler: relayPool,
},
});
// 4. Start the gateway
await gateway.start();
console.log("Gateway is running, exposing the MCP server to Nostr.");
// To stop the gateway: await gateway.stop();
```
## Next Steps
This concludes the core components of the SDK. The final section provides practical examples of how to use these components together.
- **[Tutorials](/tutorials/client-server-communication)**
================
File: docs/ts-sdk/proxy/overview.md
================
---
title: Proxy Overview
description: A client-side bridging component for the @contextvm/sdk.
---
# Proxy
The `NostrMCPProxy` is a powerful, client-side bridging component in the `@contextvm/sdk`. Its primary function is to act as a local proxy that translates communication between a standard MCP client and a remote, Nostr-based MCP server.
## Functionality Overview
The proxy manages two transports simultaneously:
1. **MCP Host Transport**: This is a standard MCP transport (like `StdioServerTransport`) that communicates with a local MCP client application.
2. **Nostr Client Transport**: This is a [`NostrClientTransport`](/transports/nostr-client-transport) that communicates with the remote MCP server over the Nostr network.
The proxy sits in the middle, seamlessly forwarding messages between these two transports. When the local client sends a request, the proxy forwards it over Nostr. When the remote server sends a response, the proxy relays it back to the local client.
## Use Cases and Capabilities
The `NostrMCPProxy` is particularly useful in the following scenarios:
- **Integrating with Existing Clients**: If you have an existing MCP client that does not have native Nostr support, you can use the proxy to enable it to communicate with Nostr-based MCP servers without modifying the client's code. The client simply connects to the proxy's local transport.
- **Simplifying Client-Side Logic**: The proxy abstracts away all the complexities of Nostr communication (signing, relay management, encryption), allowing your main client application to remain simple and focused on its core tasks.
- **Local Development and Testing**: The proxy can be a valuable tool for local development, allowing you to easily test a client against a remote Nostr server.
## `NostrMCPProxyOptions`
To create a `NostrMCPProxy`, you need to provide a configuration object that implements the `NostrMCPProxyOptions` interface:
```typescript
export interface NostrMCPProxyOptions {
mcpHostTransport: Transport;
nostrTransportOptions: NostrTransportOptions;
}
```
- **`mcpHostTransport`**: An instance of a server-side MCP transport that the local client will connect to. For example, `new StdioServerTransport()`.
- **`nostrTransportOptions`**: The full configuration object required by the `NostrClientTransport`. This includes the `signer`, `relayHandler`, and the remote `serverPubkey`.
## Usage Example
This example demonstrates how to create a proxy that listens for a local client over standard I/O and connects to a remote server over Nostr.
```typescript
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { NostrMCPProxy } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
// 1. Configure the signer and relay handler for the Nostr connection
const signer = new PrivateKeySigner("your-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);
const REMOTE_SERVER_PUBKEY = "remote-server-public-key";
// 2. Configure the transport for the local client
// In this case, a stdio transport that the local client can connect to
const hostTransport = new StdioServerTransport();
// 3. Create the proxy instance
const proxy = new NostrMCPProxy({
mcpHostTransport: hostTransport,
nostrTransportOptions: {
signer,
relayHandler: relayPool,
serverPubkey: REMOTE_SERVER_PUBKEY,
},
});
// 4. Start the proxy
await proxy.start();
console.log("Proxy is running. Connect your local MCP client.");
// To stop the proxy: await proxy.stop();
```
In this setup, a separate MCP client process could connect to this proxy's `StdioServerTransport` and it would be transparently communicating with the remote server on Nostr.
## Next Steps
Next, we'll look at the server-side equivalent of the proxy:
- **[Gateway](/overview)**
================
File: docs/ts-sdk/relay/applesauce-relay-pool.md
================
---
title: ApplesauceRelayPool
description: An advanced relay handler implementation using the applesauce-relay library for the @contextvm/sdk.
---
# `ApplesauceRelayPool`
The `ApplesauceRelayPool` is an advanced implementation of the [`RelayHandler`](/relay/relay-handler-interface) interface that uses the `applesauce-relay` library. It provides sophisticated relay management with automatic reconnection, connection monitoring, and robust subscription handling.
## Overview
The `ApplesauceRelayPool` offers enhanced features compared to the basic [`SimpleRelayPool`](/relay/simple-relay-pool):
- **Automatic Connection Management**: Uses `RelayPool` for efficient connection handling
- **Connection Monitoring**: Monitors relay connections and automatically resubscribes when connections are lost
- **Retry Logic**: Built-in retry mechanisms for failed operations
- **Observable-based Architecture**: Leverages RxJS-style observables for event handling
- **Advanced Subscription Management**: Persistent subscriptions with automatic reconnection
This implementation is ideal for applications that require more sophisticated relay management and better resilience against network interruptions.
## `constructor(relayUrls: string[])`
The constructor takes a single argument:
- **`relayUrls`**: An array of strings, where each string is the URL of a Nostr relay (e.g., `wss://relay.damus.io`).
## Usage Example
```typescript
import { ApplesauceRelayPool } from "@contextvm/sdk";
import { NostrClientTransport } from "@contextvm/sdk";
// 1. Define the list of relays you want to connect to
const myRelays = [
"wss://relay.damus.io",
"wss://relay.primal.net",
"wss://nos.lol",
];
// 2. Create an instance of the ApplesauceRelayPool
const relayPool = new ApplesauceRelayPool(myRelays);
// 3. Pass the instance to a transport
const transport = new NostrClientTransport({
relayHandler: relayPool,
// ... other options
});
```
## How It Works
The `ApplesauceRelayPool` implements the `RelayHandler` interface using the `applesauce-relay` library:
### Connection Management
- **`connect()`**: Validates relay URLs and initializes the `RelayPool`. The pool automatically manages connections to relays as needed.
- **`disconnect()`**: Closes all active subscriptions and clears internal state. Note that the underlying `RelayPool` manages connections automatically.
### Event Publishing
- **`publish(event)`**: Uses `relayGroup.publish()` which includes automatic retry logic. The method returns a Promise that resolves when the publish operation completes.
### Subscription Management
- **`subscribe(filters, onEvent, onEose)`**: Creates a persistent subscription using `relayGroup.subscription()` with automatic reconnection. Subscriptions are tracked internally for lifecycle management.
- **`unsubscribe()`**: Closes all active subscriptions and clears the internal subscription tracking.
### Advanced Features
#### Connection Monitoring
The pool automatically monitors relay connections and triggers resubscription when connections are lost:
```typescript
private setupConnectionMonitoring(): void {
this.pool.relays$.subscribe((relays) => {
relays.forEach((relay) => {
relay.connected$.subscribe((connected) => {
if (!connected) {
this.resubscribeAll();
}
});
});
});
}
```
#### Automatic Resubscription
When a relay connection is lost and reestablished, the pool automatically resubscribes to all active subscriptions:
```typescript
private resubscribeAll(): void {
this.subscriptions.forEach((sub) => {
if (sub.closer) sub.closer.unsubscribe();
sub.closer = this.createSubscription(
sub.filters,
sub.onEvent,
sub.onEose,
);
});
}
```
#### Error Handling
The implementation includes comprehensive error handling for both publishing and subscription operations:
- **Publish Errors**: Logs warnings for failed publishes but doesn't reject the Promise unless there's a critical error
- **Subscription Errors**: Removes failed subscriptions from tracking and logs the error
## Key Differences from SimpleRelayPool
| Feature | SimpleRelayPool | ApplesauceRelayPool |
| ---------------------------- | ------------------------------------ | ----------------------------------------- |
| **Library** | `nostr-tools` | `applesauce-relay` |
| **Connection Management** | Manual connection tracking | Automatic connection management |
| **Reconnection** | Manual reconnection logic | Automatic reconnection with monitoring |
| **Retry Logic** | Basic retry with exponential backoff | Built-in retry mechanisms |
| **Subscription Persistence** | Manual resubscription | Automatic resubscription on reconnect |
| **Error Handling** | Basic error logging | Comprehensive error handling with cleanup |
## When to Use ApplesauceRelayPool
Consider using `ApplesauceRelayPool` when:
- You need robust connection management and automatic reconnection
- Your application requires high availability and resilience
- You want advanced subscription management with automatic recovery
- You're building a production application that needs to handle network interruptions gracefully
For simpler use cases or when you want to minimize dependencies, the [`SimpleRelayPool`](/relay/simple-relay-pool) may be sufficient.
## Next Steps
- Learn how to build a custom relay handler: **[Custom Relay Handler](/relay/custom-relay-handler)**
- Understand the relay handler interface: **[Relay Handler Interface](/relay/relay-handler-interface)**
================
File: docs/ts-sdk/relay/custom-relay-handler.md
================
---
title: Custom Relay Handler Development
description: Learn how to create a custom relay handler for the @contextvm/sdk.
---
# Custom Relay Handler Development
The `@contextvm/sdk`'s-pluggable architecture, centered around the [`RelayHandler`](/relay/relay-handler-interface) interface, allows developers to implement custom logic for managing Nostr-relay connections. This is particularly useful for advanced use cases that require more sophisticated behavior than what the default [`SimpleRelayPool`](/relay/simple-relay-pool) provides.
## Why Create a Custom Relay Handler?
You might want to create a custom `RelayHandler` for several reasons:
- **Intelligent Relay Selection**: To dynamically select relays based on performance, reliability, or the specific type of data being requested. For example, you might use a different set of relays for fetching user metadata versus broadcasting messages.
- **Auth Relays**: To integrate with auth relays that require authentication or specific connection logic.
- **Dynamic Relay Discovery**: To discover and connect to new relays at runtime, rather than using a static list.
- **Custom Caching**: To implement a custom caching layer to reduce redundant requests to relays.
- **Resiliency and-failover**: To build more robust-failover logic, such as automatically retrying failed connections or switching to backup relays.
## Non-Blocking Subscription Requirement
A critical requirement for implementing the `RelayHandler` interface is that the `subscribe` method must be **non-blocking**. This design ensures that the transport layer can create multiple subscriptions concurrently without waiting for each one to complete.
### Key Implementation Principles
1. **Immediate Return**: The `subscribe` method should return immediately after initiating the subscription
2. **Internal State Management**: Store active subscriptions internally for lifecycle management
3. **Automatic Reconnection**: Handle resubscription when connections are reestablished
## Implementing the `RelayHandler` Interface
To create a custom relay handler, you need to create a class that implements the `RelayHandler` interface. This involves implementing five methods: `connect`, `disconnect`, `publish`, `subscribe`, and `unsubscribe`.
### Implementation Pattern For Non-Blocking Subscriptions
```typescript
class MyRelayHandler implements RelayHandler {
private subscriptions: Array<{
filters: Filter[];
onEvent: (event: NostrEvent) => void;
onEose?: () => void;
closer?: SubCloser; // Or similar subscription management object
}> = [];
async connect(): Promise<void> {
// Connect to the relays
}
async disconnect(relayUrls?: string[]): Promise<void> {
// Disconnect from the relays
}
async publish(event: NostrEvent): Promise<void> {
// Publish the event to the relays
}
async subscribe(
filters: Filter[],
onEvent: (event: NostrEvent) => void,
onEose?: () => void,
): Promise<void> {
// Create the subscription (non-blocking)
const closer = this.pool.subscribeMany(relayUrls, filters, {
onevent: onEvent,
oneose: onEose,
});
// Store the subscription for management
this.subscriptions.push({ filters, onEvent, onEose, closer });
}
unsubscribe(): void {
// Close all active subscriptions
this.subscriptions.forEach((sub) => sub.closer?.close());
this.subscriptions = [];
}
}
```
This pattern is used by both [`SimpleRelayPool`](/relay/simple-relay-pool) and [`ApplesauceRelayPool`](/relay/applesauce-relay-pool) implementations.
## Using Your Custom Relay Handler
Once your custom handler class is created, you can instantiate it and pass it to any component that requires a `RelayHandler`, such as the `NostrClientTransport` or `NostrServerTransport`. The SDK will then use your custom logic for all relay interactions.
## Next Steps
With the `Relay` component covered, we will now look at the high-level bridging components provided by the SDK.
- **[Proxy](/proxy/overview)**
- **[Gateway](/overview)**
================
File: docs/ts-sdk/relay/relay-handler-interface.md
================
---
title: RelayHandler Interface
description: An interface for managing Nostr relay connections.
---
# `RelayHandler` Interface
The `RelayHandler` interface is another crucial abstraction in the `@contextvm/sdk`. It defines the standard for managing connections to Nostr relays, which are the backbone of the Nostr network responsible for message propagation.
## Purpose and Design
The `RelayHandler`'s purpose is to abstract the complexities of relay management, including:
- Connecting and disconnecting from a set of relays.
- Subscribing to events with specific filters.
- Publishing events to the network.
- Handling relay-specific logic, such as connection retries, timeouts, and relay selection.
By depending on this interface, the SDK's transports can remain agnostic about the specific relay management strategy being used. This allows developers to plug in different relay handlers to suit their needs.
## Non-Blocking Subscription Model
A critical aspect of the `RelayHandler` interface is that the `subscribe` method must be **non-blocking**. This design choice ensures that transports can create multiple subscriptions without waiting for each one to complete, allowing for efficient concurrent event handling.
### Key Design Principles
1. **Immediate Return**: The `subscribe` method should return immediately after initiating the subscription, without awaiting the subscription's completion.
2. **Internal Subscription Management**: Relay handlers must maintain active subscriptions internally, typically using an array or similar data structure to track subscription state.
3. **Automatic Reconnection**: Subscriptions should automatically resubscribe when connections are reestablished, ensuring continuous event delivery even during network interruptions.
## Interface Definition
The `RelayHandler` interface is defined in [`core/interfaces.ts`](/core/interfaces#relayhandler) and includes several key methods:
```typescript
export interface RelayHandler {
connect(): Promise<void>;
disconnect(relayUrls?: string[]): Promise<void>;
publish(event: NostrEvent): Promise<void>;
subscribe(
filters: Filter[],
onEvent: (event: NostrEvent) => void,
onEose?: () => void,
): Promise<void>;
unsubscribe(): void;
}
```
- `connect()`: Establishes connections to the configured relays.
- `disconnect()`: Closes connections to all relays.
- `subscribe(filters, onEvent)`: Creates a subscription on the connected relays, listening for events that match the provided filters and passing them to the `onEvent` callback, it also accepts an optional `onEose` callback that is called when the relay reach "end of stored events".
- `unsubscribe()`: Closes all active subscriptions.
- `publish(event)`: Publishes a Nostr event to the connected relays.
## Implementations
The SDK provides a default implementation for common use cases and allows for custom implementations for advanced scenarios.
- **[SimpleRelayPool](/relay/simple-relay-pool)**: The default implementation, which manages a pool of relays and handles connection and subscription logic.
- **[Custom Relay Handler](/relay/custom-relay-handler)**: For creating custom relay handlers that integrate with specific relay management systems, such as auth relays or custom caching.
## Next Steps
- Learn about the default implementation: **[SimpleRelayPool](/relay/simple-relay-pool)**
- Learn how to create your own: **[Custom Relay Handler](/relay/custom-relay-handler)**
================
File: docs/ts-sdk/relay/simple-relay-pool.md
================
---
title: SimpleRelayPool
description: A default relay handler implementation for the @contextvm/sdk.
---
# `SimpleRelayPool`
The `SimpleRelayPool` is the default implementation of the [`RelayHandler`](/relay/relay-handler-interface) interface provided by the `@contextvm/sdk`. It uses the `SimplePool` from the `nostr-tools` library to manage connections to a list of specified relays.
## Overview
The `SimpleRelayPool` provides a straightforward way to manage relay connections for most common use cases. Its responsibilities include:
- Connecting to a predefined list of Nostr relays.
- Publishing events to all relays in the pool.
- Subscribing to events from all relays in the pool.
- Managing the lifecycle of connections and subscriptions.
It is a simple but effective solution for applications that need to interact with a static set of relays.
## `constructor(relayUrls: string[])`
The constructor takes a single argument:
- **`relayUrls`**: An array of strings, where each string is the URL of a Nostr relay (e.g., `wss://relay.damus.io`).
## Usage Example
```typescript
import { SimpleRelayPool } from "@contextvm/sdk";
import { NostrClientTransport } from "@contextvm/sdk";
// 1. Define the list of relays you want to connect to
const myRelays = [
"wss://relay.damus.io",
"wss://relay.primal.net",
"wss://nos.lol",
];
// 2. Create an instance of the SimpleRelayPool
const relayPool = new SimpleRelayPool(myRelays);
// 3. Pass the instance to a transport
const transport = new NostrClientTransport({
relayHandler: relayPool,
// ... other options
});
```
## How It Works
The `SimpleRelayPool` wraps the `SimplePool` from `nostr-tools` and implements the methods of the `RelayHandler` interface:
- **`connect()`**: Iterates through the provided `relayUrls` and calls `pool.ensureRelay()` for each one, which establishes a connection if one doesn't already exist.
- **`disconnect()`**: Closes the connections to the specified relays.
- **`publish(event)`**: Publishes the given event to all relays in the pool by calling `pool.publish()`.
- **`subscribe(filters, onEvent)`**: Creates a subscription on all relays in the pool using `pool.subscribeMany()`. It tracks all active subscriptions so they can be closed later.
- **`unsubscribe()`**: Closes all active subscriptions that were created through the `subscribe` method.
## Limitations
The `SimpleRelayPool` is designed for simplicity. It connects to all provided relays and does not include advanced features.
For applications that require more sophisticated relay management, you may want to create a [Custom Relay Handler](/relay/custom-relay-handler).
## Next Steps
- Learn how to build a custom relay handler: **[Custom Relay Handler](/relay/custom-relay-handler)**
================
File: docs/ts-sdk/signer/custom-signer-development.md
================
---
title: Custom Signer Development
description: Learn how to create a custom signer for the @contextvm/sdk.
---
# Custom Signer Development
One of the key design features of the `@contextvm/sdk` is its modularity, which is exemplified by the [`NostrSigner`](/signer/nostr-signer-interface) interface. By creating your own implementation of this interface, you can integrate the SDK with any key management system, such as a hardware wallet, a remote signing service (like an HSM), or a browser extension.
## Why Create a Custom Signer?
While the [`PrivateKeySigner`](/signer/private-key-signer) is a common choice for most applications, there are cases where you may need to use a different approach:
- **Security is paramount**: You need to keep private keys isolated from the main application logic, for example, in a hardware security module (HSM) or a secure enclave.
- **Interacting with external wallets**: Your application needs to request signatures from a user's wallet, such as a browser extension (e.g., Alby, Noster) or a mobile wallet.
- **Complex key management**: Your application uses a more complex key management architecture that doesn't involve direct access to raw private keys.
## Implementing the `NostrSigner` Interface
To create a custom signer, you need to create a class that implements the `NostrSigner` interface. This involves implementing two main methods: `getPublicKey()` and `signEvent()`, as well as an optional `nip44` object for encryption.
### Example: A NIP-07 Browser Signer (window.nostr)
A common use case for a custom signer is in a web application that needs to interact with a Nostr browser extension (like Alby, nos2x, or Blockcore) that exposes the `window.nostr` object according to [NIP-07](https://github.com/nostr-protocol/nips/blob/master/07.md). This allows the application to request signatures and encryption from the user's wallet without ever handling private keys directly.
Here is how you could implement a `NostrSigner` that wraps the `window.nostr` object:
```typescript
import { NostrSigner } from "@contextvm/sdk";
import { UnsignedEvent, NostrEvent } from "nostr-tools";
// Define the NIP-07 window.nostr interface for type-safety
declare global {
interface Window {
nostr?: {
getPublicKey(): Promise<string>;
signEvent(event: UnsignedEvent): Promise<NostrEvent>;
nip44?: {
encrypt(pubkey: string, plaintext: string): Promise<string>;
decrypt(pubkey: string, ciphertext: string): Promise<string>;
};
};
}
}
class Nip07Signer implements NostrSigner {
constructor() {
if (!window.nostr) {
throw new Error("NIP-07 compatible browser extension not found.");
}
}
async getPublicKey(): Promise<string> {
if (!window.nostr) throw new Error("window.nostr not found.");
return await window.nostr.getPublicKey();
}
async signEvent(event: UnsignedEvent): Promise<NostrEvent> {
if (!window.nostr) throw new Error("window.nostr not found.");
return await window.nostr.signEvent(event);
}
nip44 = {
encrypt: async (pubkey: string, plaintext: string): Promise<string> => {
if (!window.nostr?.nip44) {
throw new Error("The extension does not support NIP-44 encryption.");
}
return await window.nostr.nip44.encrypt(pubkey, plaintext);
},
decrypt: async (pubkey: string, ciphertext: string): Promise<string> => {
if (!window.nostr?.nip44) {
throw new Error("The extension does not support NIP-44 decryption.");
}
return await window.nostr.nip44.decrypt(pubkey, ciphertext);
},
};
}
```
### Implementing `nip44` for Decryption
When using a NIP-07 signer, the `nip44` implementation is straightforward, as you can see in the example above. You simply delegate the calls to the `window.nostr.nip44` object.
It's important to include checks to ensure that the user's browser extension supports `nip44`, as it is an optional part of the NIP-07 specification. If the extension does not support it, you should throw an error to prevent unexpected behavior.
## Using Your Custom Signer
Once your custom signer class is created, you can instantiate it and pass it to any component that requires a `NostrSigner`, such as the `NostrClientTransport` or `NostrServerTransport`. The rest of the SDK will use your custom implementation seamlessly.
## Next Steps
With the `Signer` component covered, let's move on to the **[Relay](/relay/simple-relay-pool)** component, which handles the connection and management of Nostr relays.
================
File: docs/ts-sdk/signer/nostr-signer-interface.md
================
---
title: NostrSigner Interface
description: An interface for signing Nostr events.
---
# `NostrSigner` Interface
The `NostrSigner` interface is a central component of the `@contextvm/sdk`, defining the standard for cryptographic signing operations. Every Nostr event must be signed by a private key to be considered valid, and this interface provides a consistent, pluggable way to handle this requirement.
## Purpose and Design
The primary purpose of the `NostrSigner` is to abstract the process of event signing. By depending on this interface rather than a concrete implementation, the SDK's transports and other components can remain agnostic about how and where private keys are stored and used.
This design offers several key benefits:
- **Security**: Private keys can be managed in secure environments (e.g., web extensions, hardware wallets, dedicated signing services) without exposing them to the application logic.
- **Flexibility**: Developers can easily swap out the default signer with a custom implementation that meets their specific needs.
- **Modularity**: The signing logic is decoupled from the communication logic, leading to a cleaner, more maintainable codebase.
## Interface Definition
The `NostrSigner` interface is defined in [`core/interfaces.ts`](/core/interfaces#nostrsigner).
```typescript
export interface NostrSigner {
getPublicKey(): Promise<string>;
signEvent(event: EventTemplate): Promise<NostrEvent>;
// Optional NIP-04 encryption support (deprecated)
nip04?: {
encrypt: (pubkey: string, plaintext: string) => Promise<string>;
decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
};
// Optional NIP-44 encryption support
nip44?: {
encrypt: (pubkey: string, plaintext: string) => Promise<string>;
decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
};
}
```
- `getPublicKey()`: Asynchronously returns the public key corresponding to the signer's private key.
- `signEvent(event)`: Takes an unsigned Nostr event, signs it, and returns the signature.
- `nip04`: (Deprecated) Provides NIP-04 encryption support.
- `nip44`: Provides NIP-44 encryption support.
Any class that implements this interface can be used as a signer throughout the SDK.
## Implementations
The SDK provides a default implementation for common use cases and allows for custom implementations for advanced scenarios.
- **[PrivateKeySigner](/signer/private-key-signer)**: The default implementation, which takes a raw private key string and performs signing operations locally.
- **[Custom Signer Development](/signer/custom-signer-development)**: For creating custom signers that integrate with key management systems, such as hardware wallets or remote signing services.
## Next Steps
- Learn about the default implementation: **[PrivateKeySigner](/signer/private-key-signer)**
- Learn how to create your own: **[Custom Signer Development](/signer/custom-signer-development)**
================
File: docs/ts-sdk/signer/private-key-signer.md
================
---
title: PrivateKeySigner
description: A default signer implementation for the @contextvm/sdk.
---
# `PrivateKeySigner`
The `PrivateKeySigner` is the default implementation of the [`NostrSigner`](/signer/nostr-signer-interface) interface provided by the `@contextvm/sdk`. It is a straightforward and easy-to-use signer that operates directly on a raw private key provided as a hexadecimal string.
## Overview
The `PrivateKeySigner` is designed for scenarios where the private key is readily available in the application's environment. It handles all the necessary cryptographic operations locally, including:
- Deriving the corresponding public key.
- Signing Nostr events.
- Encrypting and decrypting messages using NIP-44.
## `constructor(privateKey: string)`
The constructor takes a single argument:
- **`privateKey`**: A hexadecimal string representing the 32-byte Nostr private key.
When instantiated, the `PrivateKeySigner` will immediately convert the hex string into a `Uint8Array` and derive the public key, which is then cached for future calls to `getPublicKey()`.
## Usage Example
```typescript
import { PrivateKeySigner } from "@contextvm/sdk";
// Replace with a securely stored private key
const privateKeyHex = "your-32-byte-private-key-in-hex";
const signer = new PrivateKeySigner(privateKeyHex);
// You can now pass this signer instance to a transport
const transportOptions = {
signer: signer,
// ... other options
};
```
## Key Methods
The `PrivateKeySigner` implements all the methods required by the `NostrSigner` interface.
### `async getPublicKey(): Promise<string>`
Returns a promise that resolves with the public key corresponding to the private key provided in the constructor.
### `async signEvent(event: UnsignedEvent): Promise<NostrEvent>`
Takes an unsigned Nostr event, signs it using the private key, and returns a promise that resolves with the finalized, signed `NostrEvent`.
### `nip44`
The `PrivateKeySigner` also provides a `nip44` object that implements NIP-44 encryption and decryption. This is used internally by the transports when encryption is enabled, and it allows the `decryptMessage` function to work seamlessly with this signer.
- `encrypt(pubkey, plaintext)`: Encrypts a plaintext message for a given recipient public key.
- `decrypt(pubkey, ciphertext)`: Decrypts a ciphertext message received from a given sender public key.
## Security Considerations
While the `PrivateKeySigner` is convenient, it requires you to handle a raw private key directly in your application code. **It is crucial to manage this key securely.** Avoid hard-coding private keys in your source code. Instead, use environment variables or a secure secret management system to load the key at runtime.
For applications requiring a higher level of security, consider creating a custom signer that interacts with a hardware wallet or a remote signing service.
## Next Steps
- Learn how to build a custom signer: **[Custom Signer Development](/signer/custom-signer-development)**
================
File: docs/ts-sdk/transports/base-nostr-transport.md
================
---
title: Base Nostr Transport
description: An abstract class that provides the core functionality for all Nostr-based transports in the @contextvm/sdk.
---
# Base Nostr Transport
The `BaseNostrTransport` is an abstract class that provides the core functionality for all Nostr-based transports in the `@contextvm/sdk`. It serves as the foundation for the [`NostrClientTransport`](/transports/nostr-client-transport) and [`NostrServerTransport`](/transports/nostr-server-transport), handling the common logic for connecting to relays, managing subscriptions, and converting messages between the MCP and Nostr formats.
## Core Responsibilities
The `BaseNostrTransport` is responsible for:
- **Connection Management**: Establishing and terminating connections to the Nostr relay network via a `RelayHandler`.
- **Event Serialization**: Converting MCP JSON-RPC messages into Nostr events and vice-versa.
- **Cryptographic Operations**: Signing Nostr events using a `NostrSigner`.
- **Message Publishing**: Publishing events to the Nostr network.
- **Subscription Management**: Creating and managing subscriptions to listen for relevant events.
- **Encryption Handling**: Managing the encryption and decryption of messages based on the configured `EncryptionMode`.
## `BaseNostrTransportOptions`
When creating a transport that extends `BaseNostrTransport`, you must provide a configuration object that implements the `BaseNostrTransportOptions` interface:
```typescript
export interface BaseNostrTransportOptions {
signer: NostrSigner;
relayHandler: RelayHandler;
encryptionMode?: EncryptionMode;
}
```
- **`signer`**: An instance of a `NostrSigner` for signing events. This is a required parameter.
- **`relayHandler`**: An instance of a `RelayHandler` for managing relay connections. This is a required parameter.
- **`encryptionMode`**: An optional `EncryptionMode` enum that determines the encryption policy for the transport. Defaults to `OPTIONAL`.
## Key Methods
The `BaseNostrTransport` provides several protected methods that are used by its subclasses to implement their specific logic:
- `connect()`: Connects to the configured Nostr relays.
- `disconnect()`: Disconnects from the relays and clears subscriptions.
- `subscribe(filters, onEvent)`: Subscribes to Nostr events that match the given filters.
- `sendMcpMessage(...)`: Converts an MCP message to a Nostr event, signs it, optionally encrypts it, and publishes it to the network.
- `createSubscriptionFilters(...)`: A helper method to create standard filters for listening to messages directed at a specific public key.
## How It Fits Together
The `BaseNostrTransport` encapsulates the shared logic of Nostr communication, allowing the `NostrClientTransport` and `NostrServerTransport` to focus on their specific roles in the client-server interaction model. By building on this common base, the SDK ensures consistent behavior and a unified approach to handling MCP over Nostr.
## Next Steps
Now that you understand the foundation of the Nostr transports, let's explore the concrete implementations:
- **[Nostr Client Transport](/transports/nostr-client-transport)**: For building MCP clients that communicate over Nostr.
- **[Nostr Server Transport](/transports/nostr-server-transport)**: For exposing MCP servers to the Nostr network.
================
File: docs/ts-sdk/transports/nostr-client-transport.md
================
---
title: Nostr Client Transport
description: A client-side component for communicating with MCP servers over Nostr.
---
# Nostr Client Transport
The `NostrClientTransport` is a key component of the `@contextvm/sdk`, enabling MCP clients to communicate with remote MCP servers over the Nostr network. It implements the `Transport` interface from the `@modelcontextprotocol/sdk`, making it a plug-and-play solution for any MCP client.
## Overview
The `NostrClientTransport` handles all the complexities of Nostr-based communication, including:
- Connecting to Nostr relays.
- Subscribing to events from a specific server.
- Sending MCP requests as Nostr events.
- Receiving and processing responses and notifications.
- Handling encryption and decryption of messages.
By using this transport, an MCP client can interact with a Nostr-enabled MCP server without needing to implement any Nostr-specific logic itself.
## `NostrTransportOptions`
To create an instance of `NostrClientTransport`, you must provide a configuration object that implements the `NostrTransportOptions` interface:
```typescript
export interface NostrTransportOptions extends BaseNostrTransportOptions {
serverPubkey: string;
isStateless?: boolean;
}
```
- **`serverPubkey`**: The public key of the target MCP server. The transport will only listen for events from this public key.
- **`isStateless`** (optional): When set to `true`, enables stateless mode for the client transport. In stateless mode, the client emulates the server's initialize response without requiring a full server initialization roundtrip. This enables faster startup and reduced network overhead. Default is `false`.
## Usage Example
Here's how you can use the `NostrClientTransport` with an MCP client from the `@modelcontextprotocol/sdk`:
```typescript
import { Client } from "@modelcontextprotocol/sdk/client";
import { NostrClientTransport } from "@contextvm/sdk";
import { EncryptionMode } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
// 1. Configure the signer and relay handler
const signer = new PrivateKeySigner("your-private-key"); // Replace with your actual private key
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);
// 2. Set the public key of the target server
const REMOTE_SERVER_PUBKEY = "remote-server-public-key";
// 3. Create the transport instance
const clientNostrTransport = new NostrClientTransport({
signer,
relayHandler: relayPool,
serverPubkey: REMOTE_SERVER_PUBKEY,
encryptionMode: EncryptionMode.OPTIONAL,
});
// 4. Create and connect the MCP client
const mcpClient = new Client({
name: "My Client",
version: "1.0.0",
});
await mcpClient.connect(clientNostrTransport);
// 5. Use the client to interact with the server
const tools = await mcpClient.listTools();
console.log("Available tools:", tools);
// 6. Close the connection when done
// await mcpClient.close();
```
## How It Works
1. **`start()`**: When `mcpClient.connect()` is called, it internally calls the transport's `start()` method. This method connects to the relays and subscribes to events targeting the client's public key.
- In **stateless mode** (`isStateless: true`), the client emulates the server's initialize response without sending it over the network, skipping the `notifications/initialized` message exchange.
- In **standard mode** (`isStateless: false` or undefined), the client performs the full initialization roundtrip with the server.
2. **`send(message)`**: When you call an MCP method like `mcpClient.listTools()`, the client creates a JSON-RPC request and passes it to the transport's `send()` method. The transport then:
- Wraps the message in a Nostr event.
- Signs the event.
- Optionally encrypts it.
- Publishes it to the relays, targeting the `serverPubkey`.
3. **Event Processing**: The transport listens for incoming events. When an event is received, it is decrypted (if necessary) and converted back into a JSON-RPC message.
- If the message is a **response** (correlated by the original event ID), it is passed to the MCP client to resolve the pending request.
- If the message is a **notification**, it is emitted through the `onmessage` handler.
## Stateless Mode
The stateless mode is designed to optimize performance by reducing the initialization overhead:
- **Faster Startup**: By emulating the initialize response, the client can begin operations immediately without waiting for server response.
- **Reduced Network Overhead**: Eliminates the need for the initialization roundtrip.
- **Use Cases**: Ideal for scenarios where the client needs to quickly connect and interact with the server, such as in serverless functions or short-lived processes.
To enable stateless mode, set `isStateless: true` in the transport configuration:
```typescript
const clientNostrTransport = new NostrClientTransport({
signer,
relayHandler: relayPool,
serverPubkey: REMOTE_SERVER_PUBKEY,
encryptionMode: EncryptionMode.OPTIONAL,
isStateless: true, // Enable stateless mode
});
```
**Note**: The stateless mode might not work with all servers.
## Next Steps
Next, we will look at the server-side counterpart to this transport:
- **[Nostr Server Transport](/transports/nostr-server-transport)**: For exposing MCP servers to the Nostr network.
================
File: docs/ts-sdk/transports/nostr-server-transport.md
================
---
title: Nostr Server Transport
description: A server-side component for exposing MCP servers over Nostr.
---
# Nostr Server Transport
The `NostrServerTransport` is the server-side counterpart to the [`NostrClientTransport`](/transports/nostr-client-transport). It allows an MCP server to expose its capabilities to the Nostr network, making them discoverable and usable by any Nostr-enabled client. Like the client transport, it implements the `Transport` interface from the `@modelcontextprotocol/sdk`.
## Overview
The `NostrServerTransport` is responsible for:
- Listening for incoming MCP requests from Nostr clients.
- Managing individual client sessions and their state (e.g., initialization, encryption).
- Handling request/response correlation to ensure responses are sent to the correct client.
- Sending responses and notifications back to clients over Nostr.
- Optionally announcing the server and its capabilities to the network for public discovery.
## `NostrServerTransportOptions`
The transport is configured via the `NostrServerTransportOptions` interface:
```typescript
export interface NostrServerTransportOptions extends BaseNostrTransportOptions {
serverInfo?: ServerInfo;
isPublicServer?: boolean;
allowedPublicKeys?: string[];
/** List of capabilities that are excluded from public key whitelisting requirements */
excludedCapabilities?: CapabilityExclusion[];
}
```
- **`serverInfo`**: (Optional) Information about the server (`name`, `picture`, `website`) to be used in public announcements.
- **`isPublicServer`**: (Optional) If `true`, the transport will automatically announce the server's capabilities on the Nostr network. Defaults to `false`.
- **`allowedPublicKeys`**: (Optional) A list of client public keys that are allowed to connect. If not provided, any client can connect.
- **`excludedCapabilities`**: (Optional) A list of capabilities that are excluded from public key whitelisting requirements. This allows certain operations from disallowed public keys, enhancing security policy flexibility while maintaining backward compatibility.
### Capability Exclusion
The `CapabilityExclusion` interface allows you to define specific capabilities that bypass the public key whitelisting requirements:
```typescript
/**
* Represents a capability exclusion pattern that can bypass whitelisting.
* Can be either a method-only pattern (e.g., 'tools/list') or a method + name pattern (e.g., 'tools/call, get_weather').
*/
export interface CapabilityExclusion {
/** The JSON-RPC method to exclude from whitelisting (e.g., 'tools/call', 'tools/list') */
method: string;
/** Optional capability name to specifically exclude (e.g., 'get_weather') */
name?: string;
}
```
#### How Capability Exclusion Works
Capability exclusion provides fine-grained control over access by allowing specific operations to be performed even by clients that are not in the `allowedPublicKeys` list. This is useful for:
- Allowing public access to server discovery endpoints like `tools/list`
- Permitting specific tool calls from untrusted clients
- Maintaining backward compatibility with existing clients
#### Exclusion Patterns
- **Method-only exclusion**: `{ method: 'tools/list' }` - Excludes all calls to the `tools/list` method
- **Method + name exclusion**: `{ method: 'tools/call', name: 'add' }` - Excludes only the `add` tool from the `tools/call` method
## Usage Example
Here's how to use the `NostrServerTransport` with an `McpServer` from the `@modelcontextprotocol/sdk`:
```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { NostrServerTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
// 1. Configure the signer and relay pool
const signer = new PrivateKeySigner("your-server-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);
// 2. Create the McpServer instance
const mcpServer = new McpServer({
name: "demo-server",
version: "1.0.0",
});
// Register your server's tools, resources, etc.
// mcpServer.tool(...);
// 3. Create the NostrServerTransport instance
const serverNostrTransport = new NostrServerTransport({
signer: signer,
relayHandler: relayPool,
serverInfo: {
name: "My Awesome MCP Server",
website: "https://example.com",
},
allowedPublicKeys: ["trusted-client-key"], // Only allow specific clients
excludedCapabilities: [
{ method: "tools/list" }, // Allow any client to list available tools
{ method: "tools/call", name: "get_weather" }, // Allow any client to call get_weather tool
],
});
// 4. Connect the server
await mcpServer.connect(serverNostrTransport);
console.log("MCP server is running and available on Nostr.");
// Keep the process running...
// To shut down: await mcpServer.close();
```
## How It Works
1. **`start()`**: When `mcpServer.connect()` is called, the transport connects to the relays and subscribes to events targeting the server's public key. If `isPublicServer` is `true`, it also initiates the announcement process.
2. **Incoming Events**: The transport listens for events from clients. For each client, it maintains a `ClientSession`.
3. **Request Handling**: When a valid request is received from an authorized client, the transport forwards it to the `McpServer`'s internal logic via the `onmessage` handler. It replaces the request's original ID with the unique Nostr event ID to prevent ID collisions between different clients.
4. **Response Handling**: When the `McpServer` sends a response, the transport's `send()` method is called. The transport looks up the original request details from the client's session, restores the original request ID, and sends the response back to the correct client, referencing the original event ID.
5. **Announcements**: If `isPublicServer` is true, the transport sends requests to its own `McpServer` for `initialize`, `tools/list`, etc. It then formats the responses into the appropriate replaceable Nostr events (kinds 11316-11320) and publishes them.
## Session Management
The `NostrServerTransport` manages a session for each unique client public key. Each session tracks:
- If the client has completed the MCP initialization handshake.
- Whether the session is encrypted.
- A map of pending requests to correlate responses.
- The timestamp of the last activity, used for cleaning up inactive sessions.
## Security and Policy Flexibility
The capability exclusion feature provides enhanced security policy flexibility by allowing you to create a whitelist-based security model with specific exceptions. This approach is particularly useful for:
### Use Cases
1. **Public Discovery**: Allow any client to discover your server's capabilities via `tools/list` while restricting actual tool usage to authorized clients.
2. **Limited Public Access**: Permit specific, safe operations from untrusted clients while maintaining security for sensitive operations.
3. **Backward Compatibility**: Gradually introduce stricter security policies while maintaining compatibility with existing clients.
4. **Tiered Access**: Create different levels of access where certain capabilities are available to all clients, while others require explicit authorization.
## Next Steps
Now that you understand how the transports work, let's dive into the **[Signer](/signer/nostr-signer-interface)**, the component responsible for cryptographic signatures.
================
File: docs/ts-sdk/tutorials/client-server-communication.md
================
---
title: Tutorial Client-Server Communication
description: A step-by-step guide to setting up a basic MCP client and server that communicate directly over the Nostr network using the @contextvm/sdk.
---
# Tutorial: Client-Server Communication
This tutorial provides a complete, step-by-step guide to setting up a basic MCP client and server that communicate directly over the Nostr network using the `@contextvm/sdk`.
## Objective
We will build two separate scripts:
1. `server.ts`: An MCP server that exposes a simple "echo" tool.
2. `client.ts`: An MCP client that connects to the server, lists the available tools, and calls the "echo" tool.
## Prerequisites
- You have completed the [Quick Overview](/getting-started/quick-overview/).
- You have two Nostr private keys (one for the server, one for the client). You can generate new keys using various tools, or by running `nostr-tools` commands.
---
## 1. The Server (`server.ts`)
First, let's create the MCP server. This server will use the `NostrServerTransport` to listen for requests on the Nostr network.
Create a new file named `server.ts`:
```typescript
import { NostrServerTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
// --- Configuration ---
// IMPORTANT: Replace with your own private key
const SERVER_PRIVATE_KEY_HEX =
process.env.SERVER_PRIVATE_KEY || "your-32-byte-server-private-key-in-hex";
const RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
// --- Main Server Logic ---
async function main() {
// 1. Setup Signer and Relay Pool
const signer = new PrivateKeySigner(SERVER_PRIVATE_KEY_HEX);
const relayPool = new SimpleRelayPool(RELAYS);
const serverPubkey = await signer.getPublicKey();
console.log(`Server Public Key: ${serverPubkey}`);
console.log("Connecting to relays...");
// 2. Create and Configure the MCP Server
const mcpServer = new McpServer({
name: "nostr-echo-server",
version: "1.0.0",
});
// 3. Define a simple "echo" tool
mcpServer.registerTool(
"echo",
{
title: "Echo Tool",
description: "Echoes back the provided message",
inputSchema: { message: z.string() },
},
async ({ message }) => ({
content: [{ type: "text", text: `Tool echo: ${message}` }],
}),
);
// 4. Configure the Nostr Server Transport
const serverTransport = new NostrServerTransport({
signer,
relayHandler: relayPool,
serverInfo: {
name: "CTXVM Echo Server",
},
});
// 5. Connect the server
await mcpServer.connect(serverTransport);
console.log("Server is running and listening for requests on Nostr...");
console.log("Press Ctrl+C to exit.");
}
main().catch((error) => {
console.error("Failed to start server:", error);
process.exit(1);
});
```
### Running the Server
To run the server, execute the following command in your terminal. Be sure to replace the placeholder private key or set the `SERVER_PRIVATE_KEY` environment variable.
```bash
bun run server.ts
```
The server will start, print its public key, and wait for incoming client connections.
---
## 2. The Client (`client.ts`)
Next, let's create the client that will connect to our server.
Create a new file named `client.ts`:
```typescript
import { Client } from "@modelcontextprotocol/sdk/client";
import { NostrClientTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
// --- Configuration ---
// IMPORTANT: Replace with the server's public key from the server output
const SERVER_PUBKEY = "the-public-key-printed-by-server.ts";
// IMPORTANT: Replace with your own private key
const CLIENT_PRIVATE_KEY_HEX =
process.env.CLIENT_PRIVATE_KEY || "your-32-byte-client-private-key-in-hex";
const RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
// --- Main Client Logic ---
async function main() {
// 1. Setup Signer and Relay Pool
const signer = new PrivateKeySigner(CLIENT_PRIVATE_KEY_HEX);
const relayPool = new SimpleRelayPool(RELAYS);
console.log("Connecting to relays...");
// 2. Configure the Nostr Client Transport
const clientTransport = new NostrClientTransport({
signer,
relayHandler: relayPool,
serverPubkey: SERVER_PUBKEY,
});
// 3. Create and connect the MCP Client
const mcpClient = new Client({
name: "my-client",
version: "0.0.1",
});
await mcpClient.connect(clientTransport);
console.log("Connected to server!");
// 4. List the available tools
console.log("\nListing available tools...");
const tools = await mcpClient.listTools();
console.log("Tools:", tools);
// 5. Call the "echo" tool
console.log('\nCalling the "echo" tool...');
const echoResult = await mcpClient.callTool({
name: "echo",
arguments: { message: "Hello, Nostr!" },
});
console.log("Echo result:", echoResult);
// 6. Close the connection
await mcpClient.close();
console.log("\nConnection closed.");
}
main().catch((error) => {
console.error("Client failed:", error);
process.exit(1);
});
```
### Running the Client
Open a **new terminal window** (leave the server running in the first one). Before running the client, make sure to update the `SERVER_PUBKEY` variable with the public key that your `server.ts` script printed to the console.
Then, run the client:
```bash
bun run client.ts
```
## Expected Output
If everything is configured correctly, you should see the following output in the client's terminal:
```
Connecting to relays...
Connected to server!
Listing available tools...
Tools: {
tools: [
{
name: 'echo',
description: 'Replies with the input it received.',
inputSchema: { ... }
}
]
}
Calling the "echo" tool...
Echo result: You said: Hello, Nostr!
Connection closed.
```
And that's it! You've successfully created an MCP client and server that communicate securely and decentrally over the Nostr network.
================
File: docs/ts-sdk/quick-overview.md
================
---
title: Quick Overview
description: An overview of the @contextvm/sdk, including its modules and core concepts.
---
# SDK Quick Overview
This overview introduces the essential modules and core concepts of the `@contextvm/sdk`. Understanding these fundamentals will help you leverage the full power of the ContextVM protocol.
## Installation
`@contextvm/sdk` is distributed as an NPM package, making it easy to integrate into your project.
## Install the SDK
Run the following command in your terminal:
```bash
npm install @contextvm/sdk
```
This will install the SDK and its dependencies into your project.
**Note:** If you are using a different package manager than NPM, just replace `npm` with the appropriate command for your package manager.
## Modules Introduction
The SDK is organized into several modules, each providing a specific set of functionalities:
- **[Core](/core/interfaces)**: Contains fundamental definitions, constants, interfaces, and utilities (e.g., encryption, serialization).
- **[Logging](/core/logging)**: SDK logging conventions, configuration and best practices (Pino-based).
- **[Transports](/transports/base-nostr-transport)**: Critical for communication, this module provides `NostrClientTransport` and `NostrServerTransport` implementations for enabling MCP over Nostr.
- **[Signer](/signer/nostr-signer-interface)**: Provides cryptographic signing capabilities required for Nostr events
- **[Relay](/relay/relay-handler-interface)**: Manages Nostr relay connections, abstracting the complexity of relay interactions.
- **[Proxy](/proxy/overview)**: A client-side MCP server that connects to other servers through Nostr, exposing their capabilities locally, specially useful for clients that don't natively support Nostr transport.
- **[Gateway](/overview)**: An MCP server transport that binds to another MCP server, exposing its capabilities to the Nostr network, specially useful for servers that don't natively support Nostr transport.
## Core Concepts
The `@contextvm/sdk` is built around a few core concepts that enable the bridging of MCP and Nostr.
### Signers and Relay Handlers
At the heart of the SDK are two key interfaces:
- **`NostrSigner`**: An interface for signing Nostr events. The SDK includes a default `PrivateKeySigner`, but you can create a custom implementation to integrate with other signing mechanisms (e.g., Window.nostr for web, remote signers, etc).
- **`RelayHandler`**: An interface for managing connections to Nostr relays. The default `SimpleRelayPool` provides basic relay management, but you can implement your own logic for more sophisticated relay selection and management.
These components are fundamental for creating and broadcasting Nostr events, which are the backbone of ContextVM communication.
### Nostr Transports
The SDK provides two specialized transports to send and receive MCP messages over the Nostr network:
- [`NostrClientTransport`](/transports/nostr-client-transport): Used by MCP clients to connect to remote MCP servers exposed via Nostr.
- [`NostrServerTransport`](/transports/nostr-server-transport): Used by MCP servers to expose their capabilities through Nostr.
These transports handle the serialization of MCP messages into Nostr events and manage the communication flow.
### Bridging Components: Proxy and Gateway
To simplify integration with existing MCP applications, the SDK provides two high-level bridging components:
- [`NostrMCPProxy`](/proxy/overview): A client-side bridge that allows an MCP client to communicate with a remote MCP server over Nostr without requiring native Nostr support in the client.
- [`NostrMCPGateway`](/overview): A server-side bridge that exposes an existing MCP server to the Nostr network, allowing it to be discovered and used by Nostr-native clients.
These components abstract away the underlying transport complexities, making it easy to connect conventional MCP setups with the decentralized Nostr ecosystem.
## Next Steps
Now that you have a basic understanding of the SDK's modules and concepts, you are ready to dive deeper. Explore the **Core Modules** section to learn about the fundamental interfaces and data structures.
================
File: docs/index.md
================
---
title: ContextVM SDK Documentation
description: A comprehensive guide to the ContextVM SDK
---
# @contextvm/sdk: The Official SDK for the ContextVM Protocol
Welcome to the official documentation for the **@contextvm/sdk**, a JavaScript/TypeScript library for the Context Vending Machine (ContextVM) Protocol. This SDK provides the tools to bridge Nostr and the Model Context Protocol (MCP), enabling decentralized discovery, access and exposure of computational services.
## What is ContextVM?
The Context Vending Machine (ContextVM) protocol defines how [Nostr](https://nostr.com/) and Model Context Protocol can be used to expose MCP server capabilities. It enables standardized usage of these resources through a decentralized, cryptographically secure messaging system. By integrating MCP with Nostr, ContextVM offers:
- **Discoverability**: MCP servers can be discovered through the Nostr network without centralized registries.
- **Verifiability**: All messages are cryptographically signed using Nostr's public keys.
- **Authorization**: No complex authorization logic required, just cryptography.
- **Decentralization**: No single point of failure for service discovery or communication.
- **Protocol Interoperability**: Both MCP and ContextVMs utilize JSON-RPC patterns, enabling seamless communication.
This documentation serves as the primary entry point for developers and individuals interested in learning more about ContextVM and its SDK.
## SDK Overview
The `@contextvm/sdk` provides the necessary components to interact with the CTXVM Protocol:
- **Core Module**: Contains fundamental definitions, constants, interfaces, and utilities (e.g., encryption, serialization).
- **Transports**: Critical for communication, providing `NostrClientTransport` and `NostrServerTransport` implementations for enabling MCP over Nostr.
- **Proxy**: A client-side MCP server that connects to other servers through Nostr, exposing server capabilities locally. Particularly useful for clients that don't natively support Nostr transport.
- **Gateway**: Implements Nostr server transport, binding to another MCP server and exposing its capabilities through the Nostr network.
- **Relay**: Functionality for managing Nostr relays, abstracting relay interactions.
- **Signer**: Provides cryptographic signing capabilities required for Nostr events.
Both the Proxy and Gateway leverage Nostr transports, allowing existing MCP servers to maintain their conventional transports while gaining Nostr interoperability.
## How to Use These Docs
This documentation is structured to guide you from initial setup to advanced implementation. We recommend starting with the "Getting Started" section and then exploring the modules most relevant to your use case.
- **Getting Started**: Covers installation and a high-level overview of the SDK.
- **Core Modules**: Details the fundamental interfaces, encryption methods, and constants.
- **Transports, Signer, Relay**: Deep dives into the key components for communication and security.
- **Proxy & Gateway**: Explains how to use the bridging components.
- **Tutorials**: Provides practical, step-by-step examples.
Let's begin by setting up your environment in the [Quick Overview](getting-started/quick-overview/).
================
File: docs/index.mdx
================
---
title: ContextVM
description: The intersection of Nostr and MCP
template: splash
hero:
tagline: The intersection of Nostr and MCP
image:
file: ../../assets/contextvm-logo.svg
actions:
- text: Get Started
link: getting-started/quick-overview/
icon: right-arrow
- text: View on GitHub
link: https://github.com/contextvm/ts-sdk
icon: external
variant: minimal
---
import { CardGrid } from "@astrojs/starlight/components";
import IconLinkCard from "../../components/IconLinkCard.astro";
## Core Concepts
<CardGrid stagger>
<IconLinkCard
title="Architecture"
icon="rocket"
href="https://github.com/ContextVM/sdk/blob/master/docs/ctxvm-draft-spec.md#complete-protocol-flow"
description="Learn the foundational concepts and architecture of ContextVM"
/>
<IconLinkCard
title="SDK Documentation"
icon="add-document"
href="ts-sdk/quick-overview/"
description="Explore our comprehensive documentation and implementation examples"
/>
<IconLinkCard
title="Integrations"
icon="puzzle"
href="ts-sdk/gateway/overview/#integration-scenarios"
description="Discover how ContextVM integrates MCP with Nostr"
/>
<IconLinkCard
title="Tutorials"
icon="open-book"
href="ts-sdk/tutorials/client-server-communication/"
description="Step-by-step guides to help you build with ContextVM"
/>
</CardGrid>
================================================================
End of Codebase
================================================================