totoms 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +555 -555
- package/dist/api/TotoAPIController.d.ts.map +1 -1
- package/dist/api/TotoAPIController.js +8 -2
- package/dist/api/TotoAPIController.js.map +1 -1
- package/dist/core/TotoMicroservice.d.ts +2 -1
- package/dist/core/TotoMicroservice.d.ts.map +1 -1
- package/dist/core/TotoMicroservice.js +25 -2
- package/dist/core/TotoMicroservice.js.map +1 -1
- package/dist/gale/agent/GaleAgent.d.ts +7 -0
- package/dist/gale/agent/GaleAgent.d.ts.map +1 -0
- package/dist/gale/agent/GaleAgent.js +8 -0
- package/dist/gale/agent/GaleAgent.js.map +1 -0
- package/dist/gale/agent/GaleConversationalAgent.d.ts +11 -0
- package/dist/gale/agent/GaleConversationalAgent.d.ts.map +1 -0
- package/dist/gale/agent/GaleConversationalAgent.js +50 -0
- package/dist/gale/agent/GaleConversationalAgent.js.map +1 -0
- package/dist/gale/conversation/GaleConversation.d.ts +4 -0
- package/dist/gale/conversation/GaleConversation.d.ts.map +1 -0
- package/dist/gale/conversation/GaleConversation.js +19 -0
- package/dist/gale/conversation/GaleConversation.js.map +1 -0
- package/dist/gale/integration/GaleBrokerAPI.d.ts +21 -0
- package/dist/gale/integration/GaleBrokerAPI.d.ts.map +1 -0
- package/dist/gale/integration/GaleBrokerAPI.js +99 -0
- package/dist/gale/integration/GaleBrokerAPI.js.map +1 -0
- package/dist/gale/model/AgentConversationMessage.d.ts +12 -0
- package/dist/gale/model/AgentConversationMessage.d.ts.map +1 -0
- package/dist/gale/model/AgentConversationMessage.js +3 -0
- package/dist/gale/model/AgentConversationMessage.js.map +1 -0
- package/dist/gale/model/AgentEndpoint.d.ts +16 -0
- package/dist/gale/model/AgentEndpoint.d.ts.map +1 -0
- package/dist/gale/model/AgentEndpoint.js +23 -0
- package/dist/gale/model/AgentEndpoint.js.map +1 -0
- package/dist/gale/model/AgentManifest.d.ts +7 -0
- package/dist/gale/model/AgentManifest.d.ts.map +1 -0
- package/dist/gale/model/AgentManifest.js +3 -0
- package/dist/gale/model/AgentManifest.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/model/AgentsConfiguration.d.ts +7 -0
- package/dist/model/AgentsConfiguration.d.ts.map +1 -0
- package/dist/model/AgentsConfiguration.js +3 -0
- package/dist/model/AgentsConfiguration.js.map +1 -0
- package/dist/model/TotoPathOptions.d.ts +1 -0
- package/dist/model/TotoPathOptions.d.ts.map +1 -1
- package/package.json +95 -95
package/README.md
CHANGED
|
@@ -1,555 +1,555 @@
|
|
|
1
|
-
# Toto Microservice SDK - NodeJS
|
|
2
|
-
|
|
3
|
-
The Toto Microservice SDK is a framework for building cloud-agnostic microservices. <br>
|
|
4
|
-
This is the NodeJS SDK documentation.
|
|
5
|
-
|
|
6
|
-
## Table of Contents
|
|
7
|
-
|
|
8
|
-
1. [Installation](#1-installation)
|
|
9
|
-
2. [Overview](#2-overview)
|
|
10
|
-
3. [Usage](#3-usage)
|
|
11
|
-
- [3.1. The Toto Microservice Configuration](#31-the-toto-microservice-configuration)
|
|
12
|
-
- [3.2. Create and Register APIs](#32-create-and-register-apis)
|
|
13
|
-
* [Exposing the OpenAPI Spec through Swagger UI](#exposing-the-openapi-spec-through-swagger-ui)
|
|
14
|
-
- [3.3. Use a Message Bus](#33-use-a-message-bus)
|
|
15
|
-
- [3.4. Expose MCP Tools](#34-expose-mcp-tools)
|
|
16
|
-
- [3.5. Load Secrets](#35-load-secrets)
|
|
17
|
-
- [3.6. Custom Configurations](#36-custom-configurations)
|
|
18
|
-
|
|
19
|
-
Other:
|
|
20
|
-
* [Build and Deploy on NPM](./docs/buildpublish.md)
|
|
21
|
-
|
|
22
|
-
## 1. Installation
|
|
23
|
-
|
|
24
|
-
```bash
|
|
25
|
-
npm install totoms
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
### Cloud-Specific Dependencies
|
|
29
|
-
|
|
30
|
-
Install the peer dependencies for your target cloud platform:
|
|
31
|
-
|
|
32
|
-
**AWS:**
|
|
33
|
-
```bash
|
|
34
|
-
npm install @aws-sdk/client-secrets-manager @aws-sdk/client-sns @aws-sdk/client-sqs
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
**GCP:**
|
|
38
|
-
```bash
|
|
39
|
-
npm install @google-cloud/pubsub @google-cloud/secret-manager
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## 2. Overview
|
|
43
|
-
|
|
44
|
-
Everything starts with `TotoMicroservice` and the `TotoMicroserviceConfiguration`.<br>
|
|
45
|
-
`TotoMicroservice` is the main orchestrator that coordinates your entire microservice. It initializes and manages:
|
|
46
|
-
|
|
47
|
-
- **API Controller & API Endpoints**: Express-based REST API setup with automatic endpoint registration
|
|
48
|
-
- **Message Bus & Message Handlers**: Event-driven communication via Pub/Sub and Queues. Registration and routing of event handlers to appropriate topics.
|
|
49
|
-
- **Secrets Management**: Automatic loading of secrets from your cloud provider
|
|
50
|
-
- **Service Lifecycle**: Initialization, startup, and shutdown management
|
|
51
|
-
|
|
52
|
-
The configuration is **declarative**. The goal is to make it very simple to configure a full microservice, with a syntax that will look like this:
|
|
53
|
-
|
|
54
|
-
```typescript
|
|
55
|
-
import { getHyperscalerConfiguration, SupportedHyperscalers, TotoMicroservice, TotoMicroserviceConfiguration } from 'totoms';
|
|
56
|
-
import { ControllerConfig } from "./Config";
|
|
57
|
-
import { SayHello } from './dlg/ExampleDelegate';
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const config: TotoMicroserviceConfiguration = {
|
|
61
|
-
serviceName: "toto-ms-ex1",
|
|
62
|
-
basePath: '/ex1',
|
|
63
|
-
environment: {
|
|
64
|
-
hyperscaler: process.env.HYPERSCALER as SupportedHyperscalers || "aws",
|
|
65
|
-
hyperscalerConfiguration: getHyperscalerConfiguration()
|
|
66
|
-
},
|
|
67
|
-
customConfiguration: ControllerConfig,
|
|
68
|
-
apiConfiguration: {
|
|
69
|
-
apiEndpoints: [
|
|
70
|
-
{ method: 'GET', path: '/hello', delegate: SayHello }
|
|
71
|
-
],
|
|
72
|
-
apiOptions: { noCorrelationId: true }
|
|
73
|
-
},
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
TotoMicroservice.init(config).then(microservice => {
|
|
77
|
-
microservice.start();
|
|
78
|
-
});
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
A **few things you should pay attention to**:
|
|
82
|
-
* `ControllerConfig` - that's your custom configuration class, that you can use to do any type of custom initialization and work (e.g. loading secrets). <br>
|
|
83
|
-
You can find [more details in this section](#31-the-toto-microservice-configuration)
|
|
84
|
-
|
|
85
|
-
The `TotoMicroserviceConfiguration` object specifies:
|
|
86
|
-
|
|
87
|
-
- **Service Metadata**: Service name and base path for API endpoints
|
|
88
|
-
- **Environment**: Cloud provider (AWS, GCP, Azure) information
|
|
89
|
-
- **API Configuration**: REST endpoints with their handlers
|
|
90
|
-
- **Message Bus Configuration**: Topics to subscribe to and message handlers
|
|
91
|
-
- **Custom Configuration**: Your application-specific settings
|
|
92
|
-
|
|
93
|
-
## 3. Usage
|
|
94
|
-
|
|
95
|
-
### 3.1. The Toto Microservice Configuration
|
|
96
|
-
|
|
97
|
-
The microservice is configured through the `TotoMicroserviceConfiguration` object and the `TotoControllerConfig` base class. <br>
|
|
98
|
-
As seen above, you need to define a **Custom Configuration Class** that extends the `TotoControllerConfig` base class as shown below here.
|
|
99
|
-
|
|
100
|
-
```typescript
|
|
101
|
-
import { TotoControllerConfig } from 'totoms';
|
|
102
|
-
|
|
103
|
-
export class ControllerConfig extends TotoControllerConfig {
|
|
104
|
-
|
|
105
|
-
getMongoSecretNames(): { userSecretName: string; pwdSecretName: string; } | null {
|
|
106
|
-
return null;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
getProps(): APIOptions {
|
|
110
|
-
return {}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
Some things to **note**:
|
|
117
|
-
* The `getMongoSecretNames()` method allows you to define the name of the Secrets containing user and pswd of your Mongo DB, if you choose to use it (stored in the Cloud Secrets Manager, depending on the cloud you're deploying to).
|
|
118
|
-
* The `getProps()` method allows you to do some overrides (e.g. no authentication for this service). You can explore the properties, they're well documented in the SDK.
|
|
119
|
-
|
|
120
|
-
### 3.2. Create and Register APIs
|
|
121
|
-
|
|
122
|
-
Your microservice exposes REST API endpoints using Express. <br>
|
|
123
|
-
Endpoints are defined when creating the API controller and are automatically set up.
|
|
124
|
-
|
|
125
|
-
#### Create a Toto Delegate
|
|
126
|
-
|
|
127
|
-
Every endpoint needs to be managed by a **Toto Delegate**. <br>
|
|
128
|
-
Toto Delegates extend the `TotoDelegate` abstract class.
|
|
129
|
-
|
|
130
|
-
This is how you define a Toto Delegate. <br>
|
|
131
|
-
*The following example shows a delegate that processes user creation*.
|
|
132
|
-
|
|
133
|
-
```typescript
|
|
134
|
-
import { TotoDelegate, UserContext, ValidationError, TotoRequest } from 'totoms';
|
|
135
|
-
import { Request } from 'express';
|
|
136
|
-
|
|
137
|
-
class CreateUserDelegate extends TotoDelegate<CreateUserRequest, CreateUserResponse> {
|
|
138
|
-
|
|
139
|
-
async do(req: CreateUserRequest, userContext: UserContext): Promise<CreateUserResponse> {
|
|
140
|
-
|
|
141
|
-
// Extract data from the request (already validated)
|
|
142
|
-
const { name, email } = req;
|
|
143
|
-
|
|
144
|
-
// Your business logic here
|
|
145
|
-
...
|
|
146
|
-
|
|
147
|
-
// Return the response
|
|
148
|
-
return {
|
|
149
|
-
id: newUserId,
|
|
150
|
-
name: name,
|
|
151
|
-
email: email
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
public parseRequest(req: Request): CreateUserRequest {
|
|
156
|
-
// Validate and parse the incoming Express request
|
|
157
|
-
if (!req.body.name) throw new ValidationError(400, "Name is required");
|
|
158
|
-
if (!req.body.email) throw new ValidationError(400, "Email is required");
|
|
159
|
-
|
|
160
|
-
return {
|
|
161
|
-
name: req.body.name,
|
|
162
|
-
email: req.body.email
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
interface CreateUserRequest extends TotoRequest {
|
|
168
|
-
name: string;
|
|
169
|
-
email: string;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
interface CreateUserResponse {
|
|
173
|
-
id: string;
|
|
174
|
-
name: string;
|
|
175
|
-
email: string;
|
|
176
|
-
}
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
#### Register Your Delegate
|
|
180
|
-
You can now register your delegate with its endpoint (path, route) in the `TotoMicroserviceConfiguration` object that we saw earlier.
|
|
181
|
-
|
|
182
|
-
```typescript
|
|
183
|
-
const config: TotoMicroserviceConfiguration = {
|
|
184
|
-
serviceName: "toto-ms-ex1",
|
|
185
|
-
basePath: '/ex1',
|
|
186
|
-
environment: ...,
|
|
187
|
-
...
|
|
188
|
-
apiConfiguration: {
|
|
189
|
-
apiEndpoints: [
|
|
190
|
-
{ method: 'POST', path: '/users', delegate: CreateUserDelegate }
|
|
191
|
-
]
|
|
192
|
-
},
|
|
193
|
-
};
|
|
194
|
-
```
|
|
195
|
-
|
|
196
|
-
#### Exposing the OpenAPI Spec through Swagger UI
|
|
197
|
-
**If you have** an OpenAPI Spec defined for your microservice, you can expose it through Swagger UI. <br>
|
|
198
|
-
To do that, you need to add the following to your `TotoMicroserviceConfiguration`, in the `apiConfiguration` section:
|
|
199
|
-
|
|
200
|
-
```typescript
|
|
201
|
-
apiConfiguration: {
|
|
202
|
-
...
|
|
203
|
-
openAPISpecification: { localSpecsFilePath: './openapi.yaml' }
|
|
204
|
-
},
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
After this the API Documentation will be available at: `http(s)://<your-microservice-host>:<port>/<base-path>/apidocs` <br>
|
|
208
|
-
|
|
209
|
-
**IMPORTANT** - API Documentation is ALSO available as a JSON endpoint at: `http(s)://<your-microservice-host>:<port>/<base-path>/jsondocs` <br>
|
|
210
|
-
|
|
211
|
-
---
|
|
212
|
-
|
|
213
|
-
### 3.3. Use a Message Bus
|
|
214
|
-
|
|
215
|
-
The Message Bus enables event-driven communication between microservices.<br>
|
|
216
|
-
It supports both PUSH (webhook-based from cloud Pub/Sub) and PULL (polling) delivery models, depending on your cloud provider and configuration.
|
|
217
|
-
|
|
218
|
-
#### 3.3.1. React to Messages
|
|
219
|
-
|
|
220
|
-
Message handlers are the primary way to react to events.
|
|
221
|
-
|
|
222
|
-
##### Create a Message Handler
|
|
223
|
-
|
|
224
|
-
Create a handler by **extending** `TotoMessageHandler` and implementing the required methods:
|
|
225
|
-
|
|
226
|
-
```typescript
|
|
227
|
-
import { TotoMessageHandler, TotoMessage, ProcessingResponse } from 'totoms';
|
|
228
|
-
|
|
229
|
-
class TopicRefreshedEventHandler extends TotoMessageHandler {
|
|
230
|
-
|
|
231
|
-
getHandledMessageType(): string {
|
|
232
|
-
// Return the message type this handler processes
|
|
233
|
-
return "topicRefreshed";
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
async processMessage(message: TotoMessage): Promise<ProcessingResponse> {
|
|
237
|
-
// Access message metadata
|
|
238
|
-
const correlationId = message.correlationId;
|
|
239
|
-
const messageId = message.id;
|
|
240
|
-
|
|
241
|
-
// Extract event data
|
|
242
|
-
const topicName = message.payload.name;
|
|
243
|
-
const blogUrl = message.payload.blogURL;
|
|
244
|
-
const user = message.payload.user;
|
|
245
|
-
|
|
246
|
-
// Your handler has access to context
|
|
247
|
-
this.logger.compute(correlationId, `Processing topic refresh for: ${topicName}`);
|
|
248
|
-
|
|
249
|
-
// Perform your business logic
|
|
250
|
-
await this.refreshTopic(topicName, blogUrl, user);
|
|
251
|
-
|
|
252
|
-
// Return success or failure
|
|
253
|
-
return { success: true };
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
private async refreshTopic(name: string, url: string, user: string) {
|
|
257
|
-
// Implementation here
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
##### Register a Message Handler
|
|
263
|
-
|
|
264
|
-
Register your message handlers with the message bus configuration.
|
|
265
|
-
|
|
266
|
-
**IMPORTANT NOTE:** <br>
|
|
267
|
-
* When using PubSub infrastructure, you need to register topics. <br>
|
|
268
|
-
Topics are registered by giving them:
|
|
269
|
-
* A `logical name` which is the name that will be used in the application to reference the topic.
|
|
270
|
-
* A topic identifier (e.g., ARN on AWS or fully-qualified Topic Name on GCP)
|
|
271
|
-
|
|
272
|
-
```typescript
|
|
273
|
-
import { TotoMessageBus, MessageHandlerRegistrationOptions } from 'totoms';
|
|
274
|
-
|
|
275
|
-
const messageBus = new TotoMessageBus(config, environment);
|
|
276
|
-
|
|
277
|
-
// Register topics
|
|
278
|
-
messageBus.registerTopic({
|
|
279
|
-
logicalName: "topic-events",
|
|
280
|
-
topicName: process.env.TOPIC_EVENTS_TOPIC_NAME! // From environment or secrets
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
// Register message handlers
|
|
284
|
-
const handlerOptions: MessageHandlerRegistrationOptions = {
|
|
285
|
-
topic: { logicalName: "topic-events" }
|
|
286
|
-
};
|
|
287
|
-
|
|
288
|
-
messageBus.registerMessageHandler(
|
|
289
|
-
new TopicRefreshedEventHandler(),
|
|
290
|
-
handlerOptions
|
|
291
|
-
);
|
|
292
|
-
```
|
|
293
|
-
|
|
294
|
-
When the microservice starts, it automatically subscribes to the configured topics and routes incoming messages to the appropriate handlers based on their message type.
|
|
295
|
-
|
|
296
|
-
#### 3.3.2. Publish Messages
|
|
297
|
-
|
|
298
|
-
You can always publish messages to topics.
|
|
299
|
-
|
|
300
|
-
**NOTE:**
|
|
301
|
-
* In the Message Destination, the topic is the **logical name of the topic** (see above).
|
|
302
|
-
|
|
303
|
-
```typescript
|
|
304
|
-
import { TotoMessage, MessageDestination } from 'totoms';
|
|
305
|
-
|
|
306
|
-
async function publishTopicUpdate(messageBus: any, topicId: string, topicName: string) {
|
|
307
|
-
// Create the message
|
|
308
|
-
const message = new TotoMessage({
|
|
309
|
-
type: "topicUpdated",
|
|
310
|
-
correlationId: "correlation-id-123",
|
|
311
|
-
id: topicId,
|
|
312
|
-
payload: {
|
|
313
|
-
name: topicName,
|
|
314
|
-
timestamp: new Date().toISOString()
|
|
315
|
-
}
|
|
316
|
-
});
|
|
317
|
-
|
|
318
|
-
const destination: MessageDestination = {
|
|
319
|
-
topicName: "topic-events"
|
|
320
|
-
};
|
|
321
|
-
|
|
322
|
-
await messageBus.publishMessage(destination, message);
|
|
323
|
-
}
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
##### Getting Access to the Message Bus
|
|
327
|
-
|
|
328
|
-
There are different ways to get access to the Message Bus instance:
|
|
329
|
-
|
|
330
|
-
* Through the `TotoMicroservice` singleton: <br>
|
|
331
|
-
`TotoMicroservice.getInstance().messageBus`
|
|
332
|
-
|
|
333
|
-
* Through an existing instance of `TotoMicroservice`
|
|
334
|
-
|
|
335
|
-
* In a `TotoMessageHandler` you will have `messageBus` as an instance variable: <br>
|
|
336
|
-
`this.messageBus`
|
|
337
|
-
|
|
338
|
-
* In a `TotoDelegate`, you can access it through the config or by maintaining a reference in your application
|
|
339
|
-
|
|
340
|
-
---
|
|
341
|
-
|
|
342
|
-
### 3.4. Expose MCP Tools
|
|
343
|
-
|
|
344
|
-
The SDK now supports exposing delegates as **Model Context Protocol (MCP) Tools**. This allows your microservice to be consumed by AI agents and other MCP-compatible clients.
|
|
345
|
-
|
|
346
|
-
#### Creating an MCP-Enabled Delegate
|
|
347
|
-
|
|
348
|
-
To expose a delegate as an MCP tool, extend `TotoMCPDelegate` instead of `TotoDelegate` and implement the `getToolDefinition()` method:
|
|
349
|
-
|
|
350
|
-
```typescript
|
|
351
|
-
import { TotoMCPDelegate, UserContext, TotoRequest } from 'totoms';
|
|
352
|
-
import { TotoMCPToolDefinition } from 'totoms';
|
|
353
|
-
import { Request } from 'express';
|
|
354
|
-
import z from 'zod';
|
|
355
|
-
|
|
356
|
-
export class GetTopics extends TotoMCPDelegate<GetTopicsRequest, GetTopicsResponse> {
|
|
357
|
-
|
|
358
|
-
public getToolDefinition(): TotoMCPToolDefinition {
|
|
359
|
-
return {
|
|
360
|
-
name: "getTopics",
|
|
361
|
-
title: "Get user's topics in Tome",
|
|
362
|
-
description: "Retrieves all topics associated with the authenticated user.",
|
|
363
|
-
inputSchema: z.object({}) // Define the input schema using Zod
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
async do(req: GetTopicsRequest, userContext: UserContext): Promise<GetTopicsResponse> {
|
|
368
|
-
const user = userContext.email;
|
|
369
|
-
|
|
370
|
-
// Your business logic here
|
|
371
|
-
const topics = await this.fetchTopicsForUser(user);
|
|
372
|
-
|
|
373
|
-
return { topics };
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
public parseRequest(req: Request): GetTopicsRequest {
|
|
377
|
-
// Parse Express request (for REST API usage)
|
|
378
|
-
return {};
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
private async fetchTopicsForUser(user: string) {
|
|
382
|
-
// Implementation
|
|
383
|
-
...
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
interface GetTopicsRequest extends TotoRequest {}
|
|
388
|
-
|
|
389
|
-
interface GetTopicsResponse {
|
|
390
|
-
topics: any[];
|
|
391
|
-
}
|
|
392
|
-
```
|
|
393
|
-
|
|
394
|
-
#### Registering MCP Tools
|
|
395
|
-
|
|
396
|
-
Register your MCP-enabled delegates in the `mcpConfiguration` section of your microservice configuration:
|
|
397
|
-
|
|
398
|
-
```typescript
|
|
399
|
-
import { TotoMicroservice, TotoMicroserviceConfiguration } from 'totoms';
|
|
400
|
-
import { GetTopics } from './dlg/GetTopics';
|
|
401
|
-
import { GetTopic } from './dlg/GetTopic';
|
|
402
|
-
|
|
403
|
-
const config: TotoMicroserviceConfiguration = {
|
|
404
|
-
serviceName: "tome-ms-topics",
|
|
405
|
-
basePath: '/tometopics',
|
|
406
|
-
environment: ...,
|
|
407
|
-
apiConfiguration: {
|
|
408
|
-
apiEndpoints: [
|
|
409
|
-
{ method: 'GET', path: '/topics', delegate: GetTopics }
|
|
410
|
-
]
|
|
411
|
-
},
|
|
412
|
-
mcpConfiguration: {
|
|
413
|
-
enableMCP: true,
|
|
414
|
-
serverConfiguration: {
|
|
415
|
-
name: "Tome Topics MCP Server",
|
|
416
|
-
tools: [
|
|
417
|
-
GetTopics,
|
|
418
|
-
GetTopic
|
|
419
|
-
]
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
};
|
|
423
|
-
```
|
|
424
|
-
|
|
425
|
-
#### Key Points
|
|
426
|
-
|
|
427
|
-
* **Dual Purpose**: Delegates extending `TotoMCPDelegate` can serve both as REST API endpoints AND as MCP tools
|
|
428
|
-
* **Tool Definition**: The `getToolDefinition()` method defines how the tool appears to MCP clients
|
|
429
|
-
* **Input Schema**: Use Zod schemas to define and validate tool inputs
|
|
430
|
-
* **Custom Processing**: Override `processToolRequest()` if you need custom logic for MCP tool invocations that differs from REST API handling
|
|
431
|
-
|
|
432
|
-
---
|
|
433
|
-
|
|
434
|
-
### 3.5. Load Secrets
|
|
435
|
-
|
|
436
|
-
The SDK handles secret loading from your cloud provider automatically. Access secrets through the configuration or use the `SecretsManager` directly:
|
|
437
|
-
|
|
438
|
-
```typescript
|
|
439
|
-
import { SecretsManager } from 'totoms';
|
|
440
|
-
|
|
441
|
-
const secrets = new SecretsManager({ hyperscaler: "aws" });
|
|
442
|
-
|
|
443
|
-
// Load a secret by name
|
|
444
|
-
const apiKey = await secrets.getSecret("api-key");
|
|
445
|
-
const databaseUrl = await secrets.getSecret("database-url");
|
|
446
|
-
```
|
|
447
|
-
|
|
448
|
-
Secrets are typically stored as environment variable names or secret manager references, depending on your deployment environment.
|
|
449
|
-
|
|
450
|
-
---
|
|
451
|
-
|
|
452
|
-
### 3.6. Custom Configurations
|
|
453
|
-
|
|
454
|
-
You can define your own custom configurations by extending the `TotoControllerConfig` base class.
|
|
455
|
-
|
|
456
|
-
An example:
|
|
457
|
-
|
|
458
|
-
```typescript
|
|
459
|
-
import { TotoControllerConfig } from 'totoms';
|
|
460
|
-
|
|
461
|
-
export class MyServiceConfig extends TotoControllerConfig {
|
|
462
|
-
|
|
463
|
-
apiKey: string | undefined;
|
|
464
|
-
|
|
465
|
-
async load(): Promise<void> {
|
|
466
|
-
// Load secrets using the secrets manager
|
|
467
|
-
this.apiKey = await this.secretsManager.getSecret("my-api-key");
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
getMongoSecretNames() {
|
|
471
|
-
// Return null if your service doesn't use MongoDB
|
|
472
|
-
return null;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
```
|
|
476
|
-
|
|
477
|
-
What you can do with a Custom Configuration:
|
|
478
|
-
|
|
479
|
-
1. **Load Secrets** <br>
|
|
480
|
-
You can do that by overriding the `load()` async method and using `this.secretsManager.getSecret("your-secret-name")` to load secrets.
|
|
481
|
-
|
|
482
|
-
2. **Configure MongoDB** <br>
|
|
483
|
-
Override `getMongoSecretNames()`, `getDBName()`, and `getCollections()` to configure MongoDB integration.
|
|
484
|
-
|
|
485
|
-
3. **Custom Authentication** <br>
|
|
486
|
-
Override `getCustomAuthVerifier()` to provide custom authentication logic.
|
|
487
|
-
|
|
488
|
-
## Core Components
|
|
489
|
-
|
|
490
|
-
### TotoAPIController
|
|
491
|
-
The main controller for building REST APIs with Express. Provides:
|
|
492
|
-
- Automatic route registration
|
|
493
|
-
- Built-in validation
|
|
494
|
-
- CORS support
|
|
495
|
-
- Health check endpoints
|
|
496
|
-
- File upload support
|
|
497
|
-
- API documentation generation
|
|
498
|
-
|
|
499
|
-
### TotoMicroservice
|
|
500
|
-
High-level wrapper that initializes the entire microservice stack including API controller, message bus, and environment configuration.
|
|
501
|
-
|
|
502
|
-
### TotoMessageBus
|
|
503
|
-
Unified interface for pub/sub messaging across cloud platforms:
|
|
504
|
-
- **AWS**: SNS/SQS
|
|
505
|
-
- **GCP**: Cloud Pub/Sub
|
|
506
|
-
- **Azure**: Service Bus (in development)
|
|
507
|
-
|
|
508
|
-
### TotoControllerConfig
|
|
509
|
-
Base configuration class for microservices with support for:
|
|
510
|
-
- MongoDB connection management
|
|
511
|
-
- Authentication settings
|
|
512
|
-
- Secrets management
|
|
513
|
-
- Custom validators
|
|
514
|
-
|
|
515
|
-
### Logger
|
|
516
|
-
Structured logging with correlation ID support for request tracing.
|
|
517
|
-
|
|
518
|
-
### Validator
|
|
519
|
-
Request validation framework with support for:
|
|
520
|
-
- JWT token validation
|
|
521
|
-
- Google OAuth
|
|
522
|
-
- Custom validation logic
|
|
523
|
-
|
|
524
|
-
## Cloud Platform Support
|
|
525
|
-
|
|
526
|
-
### AWS
|
|
527
|
-
- **Messaging**: SNS (topics), SQS (queues)
|
|
528
|
-
- **Secrets**: AWS Secrets Manager
|
|
529
|
-
- **Region Configuration**: Configurable per service
|
|
530
|
-
|
|
531
|
-
### GCP
|
|
532
|
-
- **Messaging**: Cloud Pub/Sub
|
|
533
|
-
- **Secrets**: Secret Manager
|
|
534
|
-
- **Project Configuration**: Uses default project credentials
|
|
535
|
-
|
|
536
|
-
### Azure
|
|
537
|
-
- **Messaging**: Service Bus (in development)
|
|
538
|
-
- **Secrets**: Key Vault (in development)
|
|
539
|
-
|
|
540
|
-
## License
|
|
541
|
-
|
|
542
|
-
MIT
|
|
543
|
-
|
|
544
|
-
## Author
|
|
545
|
-
|
|
546
|
-
nicolasances
|
|
547
|
-
|
|
548
|
-
## Contributing
|
|
549
|
-
|
|
550
|
-
Contributions are welcome! Please feel free to submit a Pull Request to the [toto-microservice-sdk repository](https://github.com/nicolasances/toto-microservice-sdk).
|
|
551
|
-
|
|
552
|
-
## Related Projects
|
|
553
|
-
|
|
554
|
-
- [Toto Ecosystem](https://github.com/nicolasances/toto)
|
|
555
|
-
- [Python Toto Microservice SDK](../python)
|
|
1
|
+
# Toto Microservice SDK - NodeJS
|
|
2
|
+
|
|
3
|
+
The Toto Microservice SDK is a framework for building cloud-agnostic microservices. <br>
|
|
4
|
+
This is the NodeJS SDK documentation.
|
|
5
|
+
|
|
6
|
+
## Table of Contents
|
|
7
|
+
|
|
8
|
+
1. [Installation](#1-installation)
|
|
9
|
+
2. [Overview](#2-overview)
|
|
10
|
+
3. [Usage](#3-usage)
|
|
11
|
+
- [3.1. The Toto Microservice Configuration](#31-the-toto-microservice-configuration)
|
|
12
|
+
- [3.2. Create and Register APIs](#32-create-and-register-apis)
|
|
13
|
+
* [Exposing the OpenAPI Spec through Swagger UI](#exposing-the-openapi-spec-through-swagger-ui)
|
|
14
|
+
- [3.3. Use a Message Bus](#33-use-a-message-bus)
|
|
15
|
+
- [3.4. Expose MCP Tools](#34-expose-mcp-tools)
|
|
16
|
+
- [3.5. Load Secrets](#35-load-secrets)
|
|
17
|
+
- [3.6. Custom Configurations](#36-custom-configurations)
|
|
18
|
+
|
|
19
|
+
Other:
|
|
20
|
+
* [Build and Deploy on NPM](./docs/buildpublish.md)
|
|
21
|
+
|
|
22
|
+
## 1. Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install totoms
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Cloud-Specific Dependencies
|
|
29
|
+
|
|
30
|
+
Install the peer dependencies for your target cloud platform:
|
|
31
|
+
|
|
32
|
+
**AWS:**
|
|
33
|
+
```bash
|
|
34
|
+
npm install @aws-sdk/client-secrets-manager @aws-sdk/client-sns @aws-sdk/client-sqs
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**GCP:**
|
|
38
|
+
```bash
|
|
39
|
+
npm install @google-cloud/pubsub @google-cloud/secret-manager
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 2. Overview
|
|
43
|
+
|
|
44
|
+
Everything starts with `TotoMicroservice` and the `TotoMicroserviceConfiguration`.<br>
|
|
45
|
+
`TotoMicroservice` is the main orchestrator that coordinates your entire microservice. It initializes and manages:
|
|
46
|
+
|
|
47
|
+
- **API Controller & API Endpoints**: Express-based REST API setup with automatic endpoint registration
|
|
48
|
+
- **Message Bus & Message Handlers**: Event-driven communication via Pub/Sub and Queues. Registration and routing of event handlers to appropriate topics.
|
|
49
|
+
- **Secrets Management**: Automatic loading of secrets from your cloud provider
|
|
50
|
+
- **Service Lifecycle**: Initialization, startup, and shutdown management
|
|
51
|
+
|
|
52
|
+
The configuration is **declarative**. The goal is to make it very simple to configure a full microservice, with a syntax that will look like this:
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import { getHyperscalerConfiguration, SupportedHyperscalers, TotoMicroservice, TotoMicroserviceConfiguration } from 'totoms';
|
|
56
|
+
import { ControllerConfig } from "./Config";
|
|
57
|
+
import { SayHello } from './dlg/ExampleDelegate';
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
const config: TotoMicroserviceConfiguration = {
|
|
61
|
+
serviceName: "toto-ms-ex1",
|
|
62
|
+
basePath: '/ex1',
|
|
63
|
+
environment: {
|
|
64
|
+
hyperscaler: process.env.HYPERSCALER as SupportedHyperscalers || "aws",
|
|
65
|
+
hyperscalerConfiguration: getHyperscalerConfiguration()
|
|
66
|
+
},
|
|
67
|
+
customConfiguration: ControllerConfig,
|
|
68
|
+
apiConfiguration: {
|
|
69
|
+
apiEndpoints: [
|
|
70
|
+
{ method: 'GET', path: '/hello', delegate: SayHello }
|
|
71
|
+
],
|
|
72
|
+
apiOptions: { noCorrelationId: true }
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
TotoMicroservice.init(config).then(microservice => {
|
|
77
|
+
microservice.start();
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
A **few things you should pay attention to**:
|
|
82
|
+
* `ControllerConfig` - that's your custom configuration class, that you can use to do any type of custom initialization and work (e.g. loading secrets). <br>
|
|
83
|
+
You can find [more details in this section](#31-the-toto-microservice-configuration)
|
|
84
|
+
|
|
85
|
+
The `TotoMicroserviceConfiguration` object specifies:
|
|
86
|
+
|
|
87
|
+
- **Service Metadata**: Service name and base path for API endpoints
|
|
88
|
+
- **Environment**: Cloud provider (AWS, GCP, Azure) information
|
|
89
|
+
- **API Configuration**: REST endpoints with their handlers
|
|
90
|
+
- **Message Bus Configuration**: Topics to subscribe to and message handlers
|
|
91
|
+
- **Custom Configuration**: Your application-specific settings
|
|
92
|
+
|
|
93
|
+
## 3. Usage
|
|
94
|
+
|
|
95
|
+
### 3.1. The Toto Microservice Configuration
|
|
96
|
+
|
|
97
|
+
The microservice is configured through the `TotoMicroserviceConfiguration` object and the `TotoControllerConfig` base class. <br>
|
|
98
|
+
As seen above, you need to define a **Custom Configuration Class** that extends the `TotoControllerConfig` base class as shown below here.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
import { TotoControllerConfig } from 'totoms';
|
|
102
|
+
|
|
103
|
+
export class ControllerConfig extends TotoControllerConfig {
|
|
104
|
+
|
|
105
|
+
getMongoSecretNames(): { userSecretName: string; pwdSecretName: string; } | null {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
getProps(): APIOptions {
|
|
110
|
+
return {}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Some things to **note**:
|
|
117
|
+
* The `getMongoSecretNames()` method allows you to define the name of the Secrets containing user and pswd of your Mongo DB, if you choose to use it (stored in the Cloud Secrets Manager, depending on the cloud you're deploying to).
|
|
118
|
+
* The `getProps()` method allows you to do some overrides (e.g. no authentication for this service). You can explore the properties, they're well documented in the SDK.
|
|
119
|
+
|
|
120
|
+
### 3.2. Create and Register APIs
|
|
121
|
+
|
|
122
|
+
Your microservice exposes REST API endpoints using Express. <br>
|
|
123
|
+
Endpoints are defined when creating the API controller and are automatically set up.
|
|
124
|
+
|
|
125
|
+
#### Create a Toto Delegate
|
|
126
|
+
|
|
127
|
+
Every endpoint needs to be managed by a **Toto Delegate**. <br>
|
|
128
|
+
Toto Delegates extend the `TotoDelegate` abstract class.
|
|
129
|
+
|
|
130
|
+
This is how you define a Toto Delegate. <br>
|
|
131
|
+
*The following example shows a delegate that processes user creation*.
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
import { TotoDelegate, UserContext, ValidationError, TotoRequest } from 'totoms';
|
|
135
|
+
import { Request } from 'express';
|
|
136
|
+
|
|
137
|
+
class CreateUserDelegate extends TotoDelegate<CreateUserRequest, CreateUserResponse> {
|
|
138
|
+
|
|
139
|
+
async do(req: CreateUserRequest, userContext: UserContext): Promise<CreateUserResponse> {
|
|
140
|
+
|
|
141
|
+
// Extract data from the request (already validated)
|
|
142
|
+
const { name, email } = req;
|
|
143
|
+
|
|
144
|
+
// Your business logic here
|
|
145
|
+
...
|
|
146
|
+
|
|
147
|
+
// Return the response
|
|
148
|
+
return {
|
|
149
|
+
id: newUserId,
|
|
150
|
+
name: name,
|
|
151
|
+
email: email
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public parseRequest(req: Request): CreateUserRequest {
|
|
156
|
+
// Validate and parse the incoming Express request
|
|
157
|
+
if (!req.body.name) throw new ValidationError(400, "Name is required");
|
|
158
|
+
if (!req.body.email) throw new ValidationError(400, "Email is required");
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
name: req.body.name,
|
|
162
|
+
email: req.body.email
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
interface CreateUserRequest extends TotoRequest {
|
|
168
|
+
name: string;
|
|
169
|
+
email: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
interface CreateUserResponse {
|
|
173
|
+
id: string;
|
|
174
|
+
name: string;
|
|
175
|
+
email: string;
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
#### Register Your Delegate
|
|
180
|
+
You can now register your delegate with its endpoint (path, route) in the `TotoMicroserviceConfiguration` object that we saw earlier.
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
const config: TotoMicroserviceConfiguration = {
|
|
184
|
+
serviceName: "toto-ms-ex1",
|
|
185
|
+
basePath: '/ex1',
|
|
186
|
+
environment: ...,
|
|
187
|
+
...
|
|
188
|
+
apiConfiguration: {
|
|
189
|
+
apiEndpoints: [
|
|
190
|
+
{ method: 'POST', path: '/users', delegate: CreateUserDelegate }
|
|
191
|
+
]
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
#### Exposing the OpenAPI Spec through Swagger UI
|
|
197
|
+
**If you have** an OpenAPI Spec defined for your microservice, you can expose it through Swagger UI. <br>
|
|
198
|
+
To do that, you need to add the following to your `TotoMicroserviceConfiguration`, in the `apiConfiguration` section:
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
apiConfiguration: {
|
|
202
|
+
...
|
|
203
|
+
openAPISpecification: { localSpecsFilePath: './openapi.yaml' }
|
|
204
|
+
},
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
After this the API Documentation will be available at: `http(s)://<your-microservice-host>:<port>/<base-path>/apidocs` <br>
|
|
208
|
+
|
|
209
|
+
**IMPORTANT** - API Documentation is ALSO available as a JSON endpoint at: `http(s)://<your-microservice-host>:<port>/<base-path>/jsondocs` <br>
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
### 3.3. Use a Message Bus
|
|
214
|
+
|
|
215
|
+
The Message Bus enables event-driven communication between microservices.<br>
|
|
216
|
+
It supports both PUSH (webhook-based from cloud Pub/Sub) and PULL (polling) delivery models, depending on your cloud provider and configuration.
|
|
217
|
+
|
|
218
|
+
#### 3.3.1. React to Messages
|
|
219
|
+
|
|
220
|
+
Message handlers are the primary way to react to events.
|
|
221
|
+
|
|
222
|
+
##### Create a Message Handler
|
|
223
|
+
|
|
224
|
+
Create a handler by **extending** `TotoMessageHandler` and implementing the required methods:
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
import { TotoMessageHandler, TotoMessage, ProcessingResponse } from 'totoms';
|
|
228
|
+
|
|
229
|
+
class TopicRefreshedEventHandler extends TotoMessageHandler {
|
|
230
|
+
|
|
231
|
+
getHandledMessageType(): string {
|
|
232
|
+
// Return the message type this handler processes
|
|
233
|
+
return "topicRefreshed";
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async processMessage(message: TotoMessage): Promise<ProcessingResponse> {
|
|
237
|
+
// Access message metadata
|
|
238
|
+
const correlationId = message.correlationId;
|
|
239
|
+
const messageId = message.id;
|
|
240
|
+
|
|
241
|
+
// Extract event data
|
|
242
|
+
const topicName = message.payload.name;
|
|
243
|
+
const blogUrl = message.payload.blogURL;
|
|
244
|
+
const user = message.payload.user;
|
|
245
|
+
|
|
246
|
+
// Your handler has access to context
|
|
247
|
+
this.logger.compute(correlationId, `Processing topic refresh for: ${topicName}`);
|
|
248
|
+
|
|
249
|
+
// Perform your business logic
|
|
250
|
+
await this.refreshTopic(topicName, blogUrl, user);
|
|
251
|
+
|
|
252
|
+
// Return success or failure
|
|
253
|
+
return { success: true };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private async refreshTopic(name: string, url: string, user: string) {
|
|
257
|
+
// Implementation here
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
##### Register a Message Handler
|
|
263
|
+
|
|
264
|
+
Register your message handlers with the message bus configuration.
|
|
265
|
+
|
|
266
|
+
**IMPORTANT NOTE:** <br>
|
|
267
|
+
* When using PubSub infrastructure, you need to register topics. <br>
|
|
268
|
+
Topics are registered by giving them:
|
|
269
|
+
* A `logical name` which is the name that will be used in the application to reference the topic.
|
|
270
|
+
* A topic identifier (e.g., ARN on AWS or fully-qualified Topic Name on GCP)
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { TotoMessageBus, MessageHandlerRegistrationOptions } from 'totoms';
|
|
274
|
+
|
|
275
|
+
const messageBus = new TotoMessageBus(config, environment);
|
|
276
|
+
|
|
277
|
+
// Register topics
|
|
278
|
+
messageBus.registerTopic({
|
|
279
|
+
logicalName: "topic-events",
|
|
280
|
+
topicName: process.env.TOPIC_EVENTS_TOPIC_NAME! // From environment or secrets
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// Register message handlers
|
|
284
|
+
const handlerOptions: MessageHandlerRegistrationOptions = {
|
|
285
|
+
topic: { logicalName: "topic-events" }
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
messageBus.registerMessageHandler(
|
|
289
|
+
new TopicRefreshedEventHandler(),
|
|
290
|
+
handlerOptions
|
|
291
|
+
);
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
When the microservice starts, it automatically subscribes to the configured topics and routes incoming messages to the appropriate handlers based on their message type.
|
|
295
|
+
|
|
296
|
+
#### 3.3.2. Publish Messages
|
|
297
|
+
|
|
298
|
+
You can always publish messages to topics.
|
|
299
|
+
|
|
300
|
+
**NOTE:**
|
|
301
|
+
* In the Message Destination, the topic is the **logical name of the topic** (see above).
|
|
302
|
+
|
|
303
|
+
```typescript
|
|
304
|
+
import { TotoMessage, MessageDestination } from 'totoms';
|
|
305
|
+
|
|
306
|
+
async function publishTopicUpdate(messageBus: any, topicId: string, topicName: string) {
|
|
307
|
+
// Create the message
|
|
308
|
+
const message = new TotoMessage({
|
|
309
|
+
type: "topicUpdated",
|
|
310
|
+
correlationId: "correlation-id-123",
|
|
311
|
+
id: topicId,
|
|
312
|
+
payload: {
|
|
313
|
+
name: topicName,
|
|
314
|
+
timestamp: new Date().toISOString()
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
const destination: MessageDestination = {
|
|
319
|
+
topicName: "topic-events"
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
await messageBus.publishMessage(destination, message);
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
##### Getting Access to the Message Bus
|
|
327
|
+
|
|
328
|
+
There are different ways to get access to the Message Bus instance:
|
|
329
|
+
|
|
330
|
+
* Through the `TotoMicroservice` singleton: <br>
|
|
331
|
+
`TotoMicroservice.getInstance().messageBus`
|
|
332
|
+
|
|
333
|
+
* Through an existing instance of `TotoMicroservice`
|
|
334
|
+
|
|
335
|
+
* In a `TotoMessageHandler` you will have `messageBus` as an instance variable: <br>
|
|
336
|
+
`this.messageBus`
|
|
337
|
+
|
|
338
|
+
* In a `TotoDelegate`, you can access it through the config or by maintaining a reference in your application
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
### 3.4. Expose MCP Tools
|
|
343
|
+
|
|
344
|
+
The SDK now supports exposing delegates as **Model Context Protocol (MCP) Tools**. This allows your microservice to be consumed by AI agents and other MCP-compatible clients.
|
|
345
|
+
|
|
346
|
+
#### Creating an MCP-Enabled Delegate
|
|
347
|
+
|
|
348
|
+
To expose a delegate as an MCP tool, extend `TotoMCPDelegate` instead of `TotoDelegate` and implement the `getToolDefinition()` method:
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
import { TotoMCPDelegate, UserContext, TotoRequest } from 'totoms';
|
|
352
|
+
import { TotoMCPToolDefinition } from 'totoms';
|
|
353
|
+
import { Request } from 'express';
|
|
354
|
+
import z from 'zod';
|
|
355
|
+
|
|
356
|
+
export class GetTopics extends TotoMCPDelegate<GetTopicsRequest, GetTopicsResponse> {
|
|
357
|
+
|
|
358
|
+
public getToolDefinition(): TotoMCPToolDefinition {
|
|
359
|
+
return {
|
|
360
|
+
name: "getTopics",
|
|
361
|
+
title: "Get user's topics in Tome",
|
|
362
|
+
description: "Retrieves all topics associated with the authenticated user.",
|
|
363
|
+
inputSchema: z.object({}) // Define the input schema using Zod
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
async do(req: GetTopicsRequest, userContext: UserContext): Promise<GetTopicsResponse> {
|
|
368
|
+
const user = userContext.email;
|
|
369
|
+
|
|
370
|
+
// Your business logic here
|
|
371
|
+
const topics = await this.fetchTopicsForUser(user);
|
|
372
|
+
|
|
373
|
+
return { topics };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
public parseRequest(req: Request): GetTopicsRequest {
|
|
377
|
+
// Parse Express request (for REST API usage)
|
|
378
|
+
return {};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private async fetchTopicsForUser(user: string) {
|
|
382
|
+
// Implementation
|
|
383
|
+
...
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
interface GetTopicsRequest extends TotoRequest {}
|
|
388
|
+
|
|
389
|
+
interface GetTopicsResponse {
|
|
390
|
+
topics: any[];
|
|
391
|
+
}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
#### Registering MCP Tools
|
|
395
|
+
|
|
396
|
+
Register your MCP-enabled delegates in the `mcpConfiguration` section of your microservice configuration:
|
|
397
|
+
|
|
398
|
+
```typescript
|
|
399
|
+
import { TotoMicroservice, TotoMicroserviceConfiguration } from 'totoms';
|
|
400
|
+
import { GetTopics } from './dlg/GetTopics';
|
|
401
|
+
import { GetTopic } from './dlg/GetTopic';
|
|
402
|
+
|
|
403
|
+
const config: TotoMicroserviceConfiguration = {
|
|
404
|
+
serviceName: "tome-ms-topics",
|
|
405
|
+
basePath: '/tometopics',
|
|
406
|
+
environment: ...,
|
|
407
|
+
apiConfiguration: {
|
|
408
|
+
apiEndpoints: [
|
|
409
|
+
{ method: 'GET', path: '/topics', delegate: GetTopics }
|
|
410
|
+
]
|
|
411
|
+
},
|
|
412
|
+
mcpConfiguration: {
|
|
413
|
+
enableMCP: true,
|
|
414
|
+
serverConfiguration: {
|
|
415
|
+
name: "Tome Topics MCP Server",
|
|
416
|
+
tools: [
|
|
417
|
+
GetTopics,
|
|
418
|
+
GetTopic
|
|
419
|
+
]
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
#### Key Points
|
|
426
|
+
|
|
427
|
+
* **Dual Purpose**: Delegates extending `TotoMCPDelegate` can serve both as REST API endpoints AND as MCP tools
|
|
428
|
+
* **Tool Definition**: The `getToolDefinition()` method defines how the tool appears to MCP clients
|
|
429
|
+
* **Input Schema**: Use Zod schemas to define and validate tool inputs
|
|
430
|
+
* **Custom Processing**: Override `processToolRequest()` if you need custom logic for MCP tool invocations that differs from REST API handling
|
|
431
|
+
|
|
432
|
+
---
|
|
433
|
+
|
|
434
|
+
### 3.5. Load Secrets
|
|
435
|
+
|
|
436
|
+
The SDK handles secret loading from your cloud provider automatically. Access secrets through the configuration or use the `SecretsManager` directly:
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
import { SecretsManager } from 'totoms';
|
|
440
|
+
|
|
441
|
+
const secrets = new SecretsManager({ hyperscaler: "aws" });
|
|
442
|
+
|
|
443
|
+
// Load a secret by name
|
|
444
|
+
const apiKey = await secrets.getSecret("api-key");
|
|
445
|
+
const databaseUrl = await secrets.getSecret("database-url");
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
Secrets are typically stored as environment variable names or secret manager references, depending on your deployment environment.
|
|
449
|
+
|
|
450
|
+
---
|
|
451
|
+
|
|
452
|
+
### 3.6. Custom Configurations
|
|
453
|
+
|
|
454
|
+
You can define your own custom configurations by extending the `TotoControllerConfig` base class.
|
|
455
|
+
|
|
456
|
+
An example:
|
|
457
|
+
|
|
458
|
+
```typescript
|
|
459
|
+
import { TotoControllerConfig } from 'totoms';
|
|
460
|
+
|
|
461
|
+
export class MyServiceConfig extends TotoControllerConfig {
|
|
462
|
+
|
|
463
|
+
apiKey: string | undefined;
|
|
464
|
+
|
|
465
|
+
async load(): Promise<void> {
|
|
466
|
+
// Load secrets using the secrets manager
|
|
467
|
+
this.apiKey = await this.secretsManager.getSecret("my-api-key");
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
getMongoSecretNames() {
|
|
471
|
+
// Return null if your service doesn't use MongoDB
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
What you can do with a Custom Configuration:
|
|
478
|
+
|
|
479
|
+
1. **Load Secrets** <br>
|
|
480
|
+
You can do that by overriding the `load()` async method and using `this.secretsManager.getSecret("your-secret-name")` to load secrets.
|
|
481
|
+
|
|
482
|
+
2. **Configure MongoDB** <br>
|
|
483
|
+
Override `getMongoSecretNames()`, `getDBName()`, and `getCollections()` to configure MongoDB integration.
|
|
484
|
+
|
|
485
|
+
3. **Custom Authentication** <br>
|
|
486
|
+
Override `getCustomAuthVerifier()` to provide custom authentication logic.
|
|
487
|
+
|
|
488
|
+
## Core Components
|
|
489
|
+
|
|
490
|
+
### TotoAPIController
|
|
491
|
+
The main controller for building REST APIs with Express. Provides:
|
|
492
|
+
- Automatic route registration
|
|
493
|
+
- Built-in validation
|
|
494
|
+
- CORS support
|
|
495
|
+
- Health check endpoints
|
|
496
|
+
- File upload support
|
|
497
|
+
- API documentation generation
|
|
498
|
+
|
|
499
|
+
### TotoMicroservice
|
|
500
|
+
High-level wrapper that initializes the entire microservice stack including API controller, message bus, and environment configuration.
|
|
501
|
+
|
|
502
|
+
### TotoMessageBus
|
|
503
|
+
Unified interface for pub/sub messaging across cloud platforms:
|
|
504
|
+
- **AWS**: SNS/SQS
|
|
505
|
+
- **GCP**: Cloud Pub/Sub
|
|
506
|
+
- **Azure**: Service Bus (in development)
|
|
507
|
+
|
|
508
|
+
### TotoControllerConfig
|
|
509
|
+
Base configuration class for microservices with support for:
|
|
510
|
+
- MongoDB connection management
|
|
511
|
+
- Authentication settings
|
|
512
|
+
- Secrets management
|
|
513
|
+
- Custom validators
|
|
514
|
+
|
|
515
|
+
### Logger
|
|
516
|
+
Structured logging with correlation ID support for request tracing.
|
|
517
|
+
|
|
518
|
+
### Validator
|
|
519
|
+
Request validation framework with support for:
|
|
520
|
+
- JWT token validation
|
|
521
|
+
- Google OAuth
|
|
522
|
+
- Custom validation logic
|
|
523
|
+
|
|
524
|
+
## Cloud Platform Support
|
|
525
|
+
|
|
526
|
+
### AWS
|
|
527
|
+
- **Messaging**: SNS (topics), SQS (queues)
|
|
528
|
+
- **Secrets**: AWS Secrets Manager
|
|
529
|
+
- **Region Configuration**: Configurable per service
|
|
530
|
+
|
|
531
|
+
### GCP
|
|
532
|
+
- **Messaging**: Cloud Pub/Sub
|
|
533
|
+
- **Secrets**: Secret Manager
|
|
534
|
+
- **Project Configuration**: Uses default project credentials
|
|
535
|
+
|
|
536
|
+
### Azure
|
|
537
|
+
- **Messaging**: Service Bus (in development)
|
|
538
|
+
- **Secrets**: Key Vault (in development)
|
|
539
|
+
|
|
540
|
+
## License
|
|
541
|
+
|
|
542
|
+
MIT
|
|
543
|
+
|
|
544
|
+
## Author
|
|
545
|
+
|
|
546
|
+
nicolasances
|
|
547
|
+
|
|
548
|
+
## Contributing
|
|
549
|
+
|
|
550
|
+
Contributions are welcome! Please feel free to submit a Pull Request to the [toto-microservice-sdk repository](https://github.com/nicolasances/toto-microservice-sdk).
|
|
551
|
+
|
|
552
|
+
## Related Projects
|
|
553
|
+
|
|
554
|
+
- [Toto Ecosystem](https://github.com/nicolasances/toto)
|
|
555
|
+
- [Python Toto Microservice SDK](../python)
|