Skip to content
Back to search

mcp-typescript-sdk

A TypeScript SDK for implementing Model Context Protocol (MCP) over MQTT, supporting both browser and Node.js environments.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/emqx--mcp-typescript-sdk/badge.svg)](/listings/emqx--mcp-typescript-sdk)

HTML

<a href="/listings/emqx--mcp-typescript-sdk"><img src="/api/listings/emqx--mcp-typescript-sdk/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install @emqx-ai/mcp-mqtt-sdk

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 674 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # @emqx-ai/mcp-mqtt-sdk
  2. A TypeScript SDK for implementing Model Context Protocol (MCP) over MQTT, supporting both browser and Node.js environments with full type safety and automatic environment detection.
  3. ## 🎯 Live Demo
  4. See this SDK in action! Check out our **[MCP AI Companion Demo](https://github.com/emqx/mcp-ai-companion-demo)** - a real-world implementation using both Python and TypeScript with this SDK to create an AI agent that can:
  5. - 🎤 Control browser audio/video functionality
  6. - 😊 Switch facial expressions and emotions
  7. - 💬 Power interactive conversational experiences
  8. - 🌐 Demonstrate cross-platform MCP communication
  9. This demo showcases how to build sophisticated AI agents using MCP over MQTT for seamless browser control and interaction.
  10. ## Features
  11. - 🚀 **Universal**: Works seamlessly in browser (WebSocket) and Node.js (TCP) environments
  12. - 🔒 **Type Safe**: Full TypeScript support with Zod schema validation for MCP protocol
  13. - 🌐 **MQTT Transport**: Uses MQTT as the transport layer for reliable MCP communication
  14. - 🏗️ **Constructor-Based**: Clean object-oriented API with proper TypeScript classes
  15. - 📋 **Standards Compliant**: Follows MCP specification v2024-11-05
  16. - 🔧 **Tool & Resource Support**: Complete support for MCP tools and resources
  17. - 🔍 **Auto Discovery**: Automatic server discovery over MQTT topics
  18. - 🌍 **Environment Detection**: Automatic browser/Node.js detection with appropriate defaults
  19. ## Requirements
  20. - Node.js >= 18
  21. ## Installation
  22. ```bash
  23. npm install @emqx-ai/mcp-mqtt-sdk
  24. ```
  25. ## Quick Start
  26. ### Creating an MCP Server
  27. ```typescript
  28. import { McpMqttServer } from '@emqx-ai/mcp-mqtt-sdk'
  29. // Create server instance
  30. const server = new McpMqttServer({
  31. // MQTT connection
  32. host: 'mqtt://localhost:1883',
  33. // Server identification
  34. serverId: 'unique-server-id-123',
  35. serverName: 'myapp/greeting-server', // Hierarchical naming
  36. // Server information
  37. name: 'My MCP Server',
  38. version: '1.0.0',
  39. // Optional configuration
  40. description: 'A sample MCP server providing greeting tools',
  41. capabilities: {
  42. tools: { listChanged: true },
  43. resources: { listChanged: true, subscribe: false },
  44. },
  45. })
  46. // Add a tool
  47. server.tool(
  48. 'greet',
  49. 'Greet someone with a personalized message',
  50. {
  51. type: 'object',
  52. properties: {
  53. name: {
  54. type: 'string',
  55. description: 'Name of the person to greet'
  56. },
  57. language: {
  58. type: 'string',
  59. enum: ['en', 'es', 'fr'],
  60. description: 'Language for greeting'
  61. }
  62. },
  63. required: ['name'],
  64. },
  65. async ({ name, language = 'en' }) => {
  66. const greetings = {
  67. en: `Hello, ${name}!`,
  68. es: `¡Hola, ${name}!`,
  69. fr: `Bonjour, ${name}!`
  70. }
  71. return {
  72. content: [{
  73. type: 'text',
  74. text: greetings[language] || greetings.en,
  75. }],
  76. }
  77. }
  78. )
  79. // Add a resource
  80. server.resource(
  81. 'config://app-settings',
  82. 'Application Settings',
  83. async () => ({
  84. contents: [{
  85. uri: 'config://app-settings',
  86. mimeType: 'application/json',
  87. text: JSON.stringify({
  88. theme: 'dark',
  89. language: 'en',
  90. notifications: true
  91. }, null, 2),
  92. }],
  93. }),
  94. {
  95. description: 'Current application configuration',
  96. mimeType: 'application/json',
  97. }
  98. )
  99. // Event handlers
  100. server.on('ready', () => {
  101. console.log('Server is ready!')
  102. console.log('Topics:', server.getTopics())
  103. })
  104. server.on('error', (error) => {
  105. console.error('Server error:', error)
  106. })
  107. // Start the server
  108. await server.start()
  109. ```
  110. ### Creating an MCP Client
  111. ```typescript
  112. import { McpMqttClient } from '@emqx-ai/mcp-mqtt-sdk'
  113. // Create client instance
  114. const client = new McpMqttClient({
  115. // MQTT connection
  116. host: 'mqtt://localhost:1883',
  117. // Client information
  118. name: 'My MCP Client',
  119. version: '1.0.0',
  120. })
  121. // Set up server discovery handler
  122. client.on('serverDiscovered', async (server) => {
  123. console.log('📡 Discovered server:', server.name, '(ID:', server.serverId, ')')
  124. try {
  125. // Connect to the discovered server using serverId
  126. await client.initializeServer(server.serverId)
  127. console.log('✅ Connected to:', server.name)
  128. // List available tools using serverId
  129. const tools = await client.listTools(server.serverId)
  130. console.log('🔧 Available tools:', tools.map(t => t.name))
  131. // Call a tool using serverId
  132. if (tools.some(t => t.name === 'greet')) {
  133. const result = await client.callTool(server.serverId, 'greet', {
  134. name: 'World',
  135. language: 'es'
  136. })
  137. console.log('🎉 Tool result:', result.content[0]?.text)
  138. }
  139. // List and read resources using serverId
  140. const resources = await client.listResources(server.serverId)
  141. console.log('📚 Available resources:', resources.map(r => r.uri))
  142. if (resources.some(r => r.uri === 'config://app-settings')) {
  143. const config = await client.readResource(server.serverId, 'config://app-settings')
  144. console.log('📄 Config:', config.contents[0]?.text)
  145. }
  146. } catch (error) {
  147. console.error('❌ Error with server:', server.name, error)
  148. }
  149. })
  150. // Connect and start discovery
  151. await client.connect()
  152. // Graceful shutdown
  153. process.on('SIGINT', async () => {
  154. await client.disconnect()
  155. process.exit(0)
  156. })
  157. ```
  158. ## API Reference
  159. ### McpMqttServer
  160. #### Constructor
  161. ```typescript
  162. new McpMqttServer(config: McpMqttServerConfig)
  163. ```
  164. **Configuration:**
  165. ```typescript
  166. interface McpMqttServerConfig {
  167. // MQTT connection settings
  168. host: string
  169. username?: string
  170. password?: string
  171. // Server identification (required)
  172. serverId: string // Unique server ID (MQTT client ID)
  173. serverName: string // Hierarchical server name (e.g., "app/feature/server")
  174. // Server information (required)
  175. name: string
  176. version: string
  177. // Optional configuration
  178. description?: string // Server description
  179. capabilities?: {
  180. prompts?: { listChanged?: boolean }
  181. resources?: { subscribe?: boolean; listChanged?: boolean }
  182. tools?: { listChanged?: boolean }
  183. }
  184. rbac?: { // Optional role-based access control
  185. roles: Array<{
  186. name: string
  187. description: string
  188. allowed_methods: string[]
  189. allowed_tools: string[] | "all"
  190. allowed_resources: string[] | "all"
  191. }>
  192. }
  193. }
  194. ```
  195. #### Methods
  196. ##### `tool(name, description, inputSchema, handler)`
  197. Register a tool that clients can call.
  198. ```typescript
  199. server.tool(
  200. 'calculate',
  201. 'Perform mathematical calculations',
  202. {
  203. type: 'object',
  204. properties: {
  205. expression: {
  206. type: 'string',
  207. description: 'Mathematical expression to evaluate'
  208. },
  209. },
  210. required: ['expression'],
  211. },
  212. async ({ expression }) => {
  213. try {
  214. // Safe evaluation - implement your own parser
  215. const result = evaluateExpression(expression)
  216. return {
  217. content: [{
  218. type: 'text',
  219. text: `${expression} = ${result}`,
  220. }],
  221. }
  222. } catch (error) {
  223. return {
  224. content: [{
  225. type: 'text',
  226. text: `Error: ${error.message}`,
  227. }],
  228. isError: true,
  229. }
  230. }
  231. }
  232. )
  233. ```
  234. ##### `resource(uri, name, handler, options?)`
  235. Register a resource that clients can read.
  236. ```typescript
  237. server.resource(
  238. 'file://logs/app.log',
  239. 'Application Logs',
  240. async () => {
  241. const logs = await readLogFile()
  242. return {
  243. contents: [{
  244. uri: 'file://logs/app.log',
  245. mimeType: 'text/plain',
  246. text: logs,
  247. }],
  248. }
  249. },
  250. {
  251. description: 'Current application log entries',
  252. mimeType: 'text/plain',
  253. }
  254. )
  255. ```
  256. ##### `start()` / `stop()`
  257. Control server lifecycle.
  258. ```typescript
  259. await server.start() // Start listening for requests
  260. await server.stop() // Gracefully shutdown
  261. ```
  262. ##### `getTopics()`
  263. Get MQTT topics used by this server.
  264. ```typescript
  265. const { request, response } = server.getTopics()
  266. ```
  267. #### Events
  268. ```typescript
  269. server.on('ready', () => console.log('Server ready'))
  270. server.on('error', (error) => console.error('Server error:', error))
  271. server.on('closed', () => console.log('Server closed'))
  272. ```
  273. ### McpMqttClient
  274. #### Client Constructor
  275. ```typescript
  276. new McpMqttClient(config: McpMqttClientConfig)
  277. ```
  278. **Configuration:**
  279. ```typescript
  280. interface McpMqttClientConfig {
  281. // MQTT connection settings
  282. host: string
  283. clientId?: string
  284. username?: string
  285. password?: string
  286. clean?: boolean
  287. keepalive?: number
  288. connectTimeout?: number
  289. reconnectPeriod?: number
  290. // Client information (required)
  291. name: string
  292. version: string
  293. // Optional configuration
  294. capabilities?: {
  295. roots?: { listChanged?: boolean }
  296. sampling?: Record<string, any>
  297. }
  298. // Advanced MQTT settings (optional)
  299. will?: {
  300. topic: string
  301. payload: string | Buffer
  302. qos?: 0 | 1 | 2
  303. retain?: boolean
  304. }
  305. properties?: Record<string, any>
  306. }
  307. ```
  308. #### Client Methods
  309. ##### Connection Management
  310. ```typescript
  311. await client.connect() // Connect to MQTT broker and start discovery
  312. await client.disconnect() // Disconnect from broker
  313. await client.initializeServer(serverId) // Initialize connection to a specific server
  314. ```
  315. ##### Tool Operations
  316. ```typescript
  317. const tools = await client.listTools(serverId)
  318. const result = await client.callTool(serverId, toolName, args)
  319. ```
  320. ##### Resource Operations
  321. ```typescript
  322. const resources = await client.listResources(serverId)
  323. const data = await client.readResource(serverId, uri)
  324. ```
  325. ##### Discovery
  326. ```typescript
  327. const discovered = client.getDiscoveredServers()
  328. const connected = client.getConnectedServers()
  329. ```
  330. #### Client Events
  331. ```typescript
  332. client.on('serverDiscovered', (server) => {
  333. console.log('Found server:', server.name, 'ID:', server.serverId)
  334. })
  335. client.on('serverInitialized', (server) => {
  336. console.log('Connected to:', server.name)
  337. })
  338. client.on('serverDisconnected', (serverId) => {
  339. console.log('Server disconnected:', serverId)
  340. })
  341. client.on('connected', () => console.log('Client connected'))
  342. client.on('disconnected', () => console.log('Client disconnected'))
  343. client.on('error', (error) => console.error('Client error:', error))
  344. ```
  345. ## MQTT Configuration
  346. The SDK supports comprehensive MQTT connection options:
  347. ```typescript
  348. interface MqttConnectionOptions {
  349. host: string // Complete connection URL (e.g., ws://localhost:8083, wss://broker.emqx.io:8084)
  350. clientId?: string // Auto-generated if not provided
  351. username?: string
  352. password?: string
  353. clean?: boolean // Clean session (default: true)
  354. keepalive?: number // Keep-alive interval in seconds
  355. connectTimeout?: number // Connection timeout in milliseconds
  356. reconnectPeriod?: number // Reconnection period in milliseconds
  357. will?: { // Last Will Testament
  358. topic: string
  359. payload: string | Buffer
  360. qos?: 0 | 1 | 2
  361. retain?: boolean
  362. };
  363. }
  364. ```
  365. ### Connection Examples
  366. The `host` parameter should be a complete connection URL:
  367. ```typescript
  368. // WebSocket connections (browser)
  369. host: 'ws://localhost:8083'
  370. host: 'wss://broker.emqx.io:8084'
  371. // TCP connections (Node.js)
  372. host: 'mqtt://localhost:1883'
  373. host: 'mqtts://broker.emqx.io:8883'
  374. ```
  375. ## Advanced Usage
  376. ### Accessing Underlying MQTT Client
  377. Both server and client provide `getMqttClient()` method to access the underlying MQTT client for custom pub/sub operations:
  378. ```typescript
  379. const mqttClient = server.getMqttClient() // or client.getMqttClient()
  380. if (mqttClient) {
  381. mqttClient.subscribe('custom/topic', { qos: 1 })
  382. mqttClient.publish('custom/topic', 'Hello World')
  383. }
  384. ```
  385. ### Custom Tool Validation
  386. ```typescript
  387. import { z } from 'zod'
  388. // Define schema for tool parameters
  389. const CalculateSchema = z.object({
  390. operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
  391. a: z.number(),
  392. b: z.number(),
  393. })
  394. server.tool(
  395. 'calculate',
  396. 'Perform arithmetic operations',
  397. {
  398. type: 'object',
  399. properties: {
  400. operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] },
  401. a: { type: 'number' },
  402. b: { type: 'number' },
  403. },
  404. required: ['operation', 'a', 'b'],
  405. },
  406. async (params) => {
  407. // Validate with Zod
  408. const { operation, a, b } = CalculateSchema.parse(params)
  409. let result: number
  410. switch (operation) {
  411. case 'add': result = a + b; break
  412. case 'subtract': result = a - b; break
  413. case 'multiply': result = a * b; break
  414. case 'divide':
  415. if (b === 0) throw new Error('Division by zero')
  416. result = a / b
  417. break
  418. }
  419. return {
  420. content: [{
  421. type: 'text',
  422. text: `${a} ${operation} ${b} = ${result}`,
  423. }],
  424. }
  425. }
  426. )
  427. ```
  428. ### Error Handling
  429. ```typescript
  430. // Server-side error handling
  431. server.tool('risky-operation', 'An operation that might fail', schema, async (params) => {
  432. try {
  433. const result = await performRiskyOperation(params)
  434. return {
  435. content: [{ type: 'text', text: `Success: ${result}` }],
  436. }
  437. } catch (error) {
  438. return {
  439. content: [{ type: 'text', text: `Operation failed: ${error.message}` }],
  440. isError: true, // Mark as error response
  441. }
  442. }
  443. })
  444. // Client-side error handling
  445. try {
  446. const result = await client.callTool(serverName, 'risky-operation', params)
  447. if (result.isError) {
  448. console.error('Tool returned error:', result.content[0]?.text)
  449. } else {
  450. console.log('Success:', result.content[0]?.text)
  451. }
  452. } catch (error) {
  453. console.error('Tool call failed:', error.message)
  454. }
  455. ```
  456. ### Resource Streaming
  457. ```typescript
  458. // Server: Streaming resource
  459. server.resource(
  460. 'stream://live-data',
  461. 'Live Data Stream',
  462. async () => {
  463. const chunks = await getLiveDataChunks()
  464. return {
  465. contents: chunks.map((chunk, index) => ({
  466. uri: `stream://live-data#${index}`,
  467. mimeType: 'application/json',
  468. text: JSON.stringify(chunk),
  469. })),
  470. }
  471. }
  472. )
  473. // Client: Read streaming resource
  474. const stream = await client.readResource(serverName, 'stream://live-data')
  475. for (const content of stream.contents) {
  476. const data = JSON.parse(content.text!)
  477. processStreamChunk(data)
  478. }
  479. ```
  480. ## Development
  481. ```bash
  482. # Install dependencies
  483. npm install
  484. # Build
  485. npm run build
  486. # Build in watch mode
  487. npm run build:watch
  488. # Run tests
  489. npm run test
  490. # Type checking
  491. npm run typecheck
  492. # Linting
  493. npm run lint
  494. npm run lint:fix
  495. ```
  496. ## Protocol Details
  497. ### MQTT Topic Structure
  498. The SDK follows the official MCP over MQTT specification topic hierarchy:
  499. ```text
  500. MCP over MQTT Topic Structure:
  501. 🗂️ Server Topics:
  502. ├── $mcp-server/{server-id}/{server-name} # Control topic (initialization)
  503. ├── $mcp-server/capability/{server-id}/{server-name} # Capability change notifications
  504. └── $mcp-server/presence/{server-id}/{server-name} # Server presence (online/offline)
  505. 🗂️ Client Topics:
  506. ├── $mcp-client/capability/{mcp-client-id} # Client capability changes
  507. └── $mcp-client/presence/{mcp-client-id} # Client presence
  508. 🗂️ RPC Communication:
  509. └── $mcp-rpc/{mcp-client-id}/{server-id}/{server-name} # Bidirectional RPC communication
  510. Example Topics:
  511. - Control: $mcp-server/server-123/myapp/greeting-server
  512. - Capability: $mcp-server/capability/server-123/myapp/greeting-server
  513. - Presence: $mcp-server/presence/server-123/myapp/greeting-server
  514. - RPC: $mcp-rpc/client-456/server-123/myapp/greeting-server
  515. ```
  516. ### Message Flow
  517. 1. **Service Discovery**: Client subscribes to `$mcp-server/presence/+/#`
  518. 2. **Server Registration**: Server publishes presence to `$mcp-server/presence/{server-id}/{server-name}`
  519. 3. **Initialization**: Client sends `initialize` request to `$mcp-server/{server-id}/{server-name}`
  520. 4. **RPC Communication**: Bidirectional communication via `$mcp-rpc/{client-id}/{server-id}/{server-name}`
  521. ### Error Codes
  522. The SDK follows JSON-RPC 2.0 error codes:
  523. - `-32700`: Parse error
  524. - `-32600`: Invalid request
  525. - `-32601`: Method not found
  526. - `-32602`: Invalid params
  527. - `-32603`: Internal error
  528. - `-32000` to `-32099`: Implementation-defined server errors
  529. ## Other Language SDKs
  530. Looking for MCP over MQTT support in other languages?
  531. - **[Python SDK](https://github.com/emqx/mcp-python-sdk)** - MCP over MQTT implementation for Python
  532. - **[Erlang SDK](https://github.com/emqx/mcp-mqtt-erl)** - MCP over MQTT implementation for Erlang
  533. - **[Paho MCP over MQTT](https://github.com/mqtt-ai/paho-mcp-over-mqtt)** - MCP over MQTT implementation in C
  534. - **[ESP MCP over MQTT](https://github.com/mqtt-ai/esp-mcp-over-mqtt)** - MCP over MQTT for ESP32/embedded devices in C
  535. ## Contributing
  536. 1. Fork the repository
  537. 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
  538. 3. Make your changes with tests
  539. 4. Run the test suite (`npm test`)
  540. 5. Submit a pull request
  541. ## License
  542. Apache License 2.0. See [LICENSE](LICENSE) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.