matimo-examples 0.1.0-alpha.11

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.
Files changed (57) hide show
  1. package/.env.example +49 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -0
  4. package/agents/decorator-pattern-agent.ts +368 -0
  5. package/agents/factory-pattern-agent.ts +253 -0
  6. package/agents/langchain-agent.ts +146 -0
  7. package/edit/edit-decorator.ts +178 -0
  8. package/edit/edit-factory.ts +138 -0
  9. package/edit/edit-langchain.ts +292 -0
  10. package/execute/execute-decorator.ts +49 -0
  11. package/execute/execute-factory.ts +46 -0
  12. package/execute/execute-langchain.ts +232 -0
  13. package/github/github-decorator.ts +326 -0
  14. package/github/github-factory.ts +355 -0
  15. package/github/github-langchain.ts +206 -0
  16. package/github/github-with-approval.ts +228 -0
  17. package/gmail/README.md +345 -0
  18. package/gmail/gmail-decorator.ts +216 -0
  19. package/gmail/gmail-factory.ts +231 -0
  20. package/gmail/gmail-langchain.ts +201 -0
  21. package/hubspot/README.md +316 -0
  22. package/hubspot/hubspot-decorator.ts +180 -0
  23. package/hubspot/hubspot-factory.ts +188 -0
  24. package/hubspot/hubspot-langchain.ts +222 -0
  25. package/logger-example.ts +40 -0
  26. package/mailchimp/README.md +321 -0
  27. package/mailchimp/mailchimp-decorator.ts +277 -0
  28. package/mailchimp/mailchimp-factory.ts +187 -0
  29. package/mailchimp/mailchimp-langchain.ts +155 -0
  30. package/notion/README.md +293 -0
  31. package/notion/notion-decorator.ts +275 -0
  32. package/notion/notion-factory.ts +256 -0
  33. package/notion/notion-langchain.ts +237 -0
  34. package/package.json +79 -0
  35. package/postgres/README.md +188 -0
  36. package/postgres/postgres-decorator.ts +198 -0
  37. package/postgres/postgres-factory.ts +180 -0
  38. package/postgres/postgres-langchain.ts +213 -0
  39. package/postgres/postgres-with-approval.ts +344 -0
  40. package/read/read-decorator.ts +154 -0
  41. package/read/read-factory.ts +121 -0
  42. package/read/read-langchain.ts +273 -0
  43. package/search/search-decorator.ts +206 -0
  44. package/search/search-factory.ts +146 -0
  45. package/search/search-langchain.ts +255 -0
  46. package/slack/README.md +339 -0
  47. package/slack/slack-decorator.ts +245 -0
  48. package/slack/slack-factory.ts +226 -0
  49. package/slack/slack-langchain.ts +242 -0
  50. package/tsconfig.json +20 -0
  51. package/twilio/README.md +309 -0
  52. package/twilio/twilio-decorator.ts +288 -0
  53. package/twilio/twilio-factory.ts +238 -0
  54. package/twilio/twilio-langchain.ts +218 -0
  55. package/web/web-decorator.ts +52 -0
  56. package/web/web-factory.ts +70 -0
  57. package/web/web-langchain.ts +163 -0
@@ -0,0 +1,316 @@
1
+ # HubSpot Tools Examples
2
+
3
+ Example directory contains **3 example patterns** showing different ways to use Matimo's HubSpot tools:
4
+ 1. **Factory Pattern** - Direct SDK execution (simplest)
5
+ 2. **Decorator Pattern** - Class-based with @tool decorators
6
+ 3. **LangChain Pattern** - AI-driven with OpenAI agent
7
+
8
+ All examples are **fully working** and demonstrate real HubSpot operations (contacts, companies, products, invoices, etc.).
9
+
10
+ ## šŸš€ Quick Start
11
+
12
+ ### 1. Create a HubSpot Service Key
13
+
14
+ 1. Go to your HubSpot workspace
15
+ 2. Click **Settings** (gear icon) → **Integrations** → **Service Keys**
16
+ 3. Click **Create service key**
17
+ 4. Enter a name like "Matimo Integration"
18
+ 5. Select required scopes
19
+
20
+ ### 2. Configure Required Scopes
21
+
22
+ Select these scopes for full functionality:
23
+
24
+ **Required Scopes:**
25
+ ```
26
+ crm.objects.contacts.read - Read contacts
27
+ crm.objects.contacts.write - Create/update contacts
28
+ crm.objects.companies.read - Read companies
29
+ crm.objects.companies.write - Create/update companies
30
+ crm.objects.products.read - Read products
31
+ crm.objects.products.write - Create/update products
32
+ crm.objects.invoices.read - Read invoices
33
+ crm.objects.invoices.write - Create/update invoices
34
+ crm.objects.deals.read - Read deals
35
+ crm.objects.deals.write - Create/update deals
36
+ crm.objects.leads.read - Read leads
37
+ crm.objects.leads.write - Create/update leads
38
+ crm.objects.line_items.read - Read line items
39
+ crm.objects.line_items.write - Create/update line items
40
+ ```
41
+
42
+ ### 3. Copy Your Service Key
43
+
44
+ Once created, copy the **Service Key** (starts with `pat-na1-` or `pat-eu1-`)
45
+
46
+ ### 4. Set Up Environment
47
+
48
+ Create a `.env` file in `examples/tools/`:
49
+
50
+ ```env
51
+ MATIMO_HUBSPOT_API_KEY=pat-na1-your-service-key-here
52
+ OPENAI_API_KEY=sk-your-openai-key-here
53
+ ```
54
+
55
+ The `OPENAI_API_KEY` is only required for the LangChain example.
56
+
57
+ ### 5. Run Examples
58
+
59
+ ```bash
60
+ # Factory Pattern (simplest, direct API calls)
61
+ pnpm hubspot:factory
62
+
63
+ # Decorator Pattern (class-based OOP approach)
64
+ pnpm hubspot:decorator
65
+
66
+ # LangChain Pattern (AI-driven agent with OpenAI)
67
+ pnpm hubspot:langchain
68
+ ```
69
+
70
+ ## šŸ“š Examples Overview
71
+
72
+ ### 1. Factory Pattern (`hubspot-factory.ts`)
73
+
74
+ **Best for:** Scripts, quick tests, CLI tools
75
+
76
+ **What it does:**
77
+ - āœ… Direct tool execution with `matimo.execute()`
78
+ - āœ… Creates contacts, companies, products, invoices
79
+ - āœ… Lists existing resources
80
+ - āœ… Retrieves specific records by ID
81
+ - āœ… Simplest implementation
82
+
83
+ **Run it:**
84
+ ```bash
85
+ pnpm hubspot:factory
86
+ ```
87
+
88
+ **Key Code:**
89
+ ```typescript
90
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
91
+
92
+ // Create a contact
93
+ const contact = await matimo.execute('hubspot-create-contact', {
94
+ email: 'john@example.com',
95
+ firstname: 'John',
96
+ lastname: 'Doe'
97
+ });
98
+
99
+ // List contacts
100
+ const contacts = await matimo.execute('hubspot-list-contacts', {
101
+ limit: 10,
102
+ properties: ['email', 'firstname', 'lastname']
103
+ });
104
+
105
+ // Create a company
106
+ const company = await matimo.execute('hubspot-create-company', {
107
+ name: 'Acme Corp',
108
+ domain: 'acme.com'
109
+ });
110
+ ```
111
+
112
+ **File:** [hubspot-factory.ts](hubspot-factory.ts)
113
+
114
+ ### 2. Decorator Pattern (`hubspot-decorator.ts`)
115
+
116
+ **Best for:** Object-oriented design, class-based applications
117
+
118
+ **What it does:**
119
+ - āœ… Class methods decorated with `@tool`
120
+ - āœ… Automatic tool execution via decorators
121
+ - āœ… Multiple operations in organized class
122
+ - āœ… Creates contacts, companies, products, invoices
123
+ - āœ… OOP-friendly approach
124
+
125
+ **Run it:**
126
+ ```bash
127
+ pnpm hubspot:decorator
128
+ ```
129
+
130
+ **Key Code:**
131
+ ```typescript
132
+ import { setGlobalMatimoInstance, tool } from '@matimo/core';
133
+
134
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
135
+ setGlobalMatimoInstance(matimo);
136
+
137
+ class HubSpotAgent {
138
+ @tool('hubspot-create-contact')
139
+ async createContact(email: string, firstname: string, lastname: string) {
140
+ // Decorator auto-executes the tool
141
+ }
142
+
143
+ @tool('hubspot-create-company')
144
+ async createCompany(name: string, domain: string) {
145
+ // Also auto-executed
146
+ }
147
+
148
+ @tool('hubspot-list-contacts')
149
+ async listContacts(limit: number, properties: string[]) {
150
+ // Decorator handles execution
151
+ }
152
+ }
153
+
154
+ const agent = new HubSpotAgent();
155
+ await agent.createContact('john@example.com', 'John', 'Doe');
156
+ await agent.createCompany('Acme Corp', 'acme.com');
157
+ const contacts = await agent.listContacts(10, ['email', 'firstname', 'lastname']);
158
+ ```
159
+
160
+ **File:** [hubspot-decorator.ts](hubspot-decorator.ts)
161
+
162
+ ### 3. LangChain Pattern (`hubspot-langchain.ts`)
163
+
164
+ **Best for:** AI-driven workflows, autonomous agents, multi-step reasoning
165
+
166
+ **What it does:**
167
+ - āœ… Real AI agent using OpenAI (GPT-4o-mini)
168
+ - āœ… LLM decides which tools to use based on natural language
169
+ - āœ… LLM generates parameters from context
170
+ - āœ… Autonomous tool execution and result processing
171
+ - āœ… Natural language conversation with the agent
172
+ - āœ… Multi-step workflows with reasoning
173
+
174
+ **Prerequisites:**
175
+ - Requires `OPENAI_API_KEY` set in `.env`
176
+ - Requires `@langchain/openai` and `langchain` dependencies
177
+
178
+ **Run it:**
179
+ ```bash
180
+ pnpm hubspot:langchain
181
+ ```
182
+
183
+ **Key Code:**
184
+ ```typescript
185
+ import { createAgent } from 'langchain';
186
+ import { ChatOpenAI } from '@langchain/openai';
187
+ import { convertToolsToLangChain } from '@matimo/core';
188
+
189
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
190
+
191
+ // Get HubSpot tools
192
+ const hubspotTools = matimo.listTools()
193
+ .filter(t => t.name.startsWith('hubspot-'));
194
+
195
+ // Convert to LangChain format
196
+ const langchainTools = await convertToolsToLangChain(
197
+ hubspotTools,
198
+ matimo
199
+ );
200
+
201
+ // Create LLM-powered agent
202
+ const model = new ChatOpenAI({ modelName: 'gpt-4o-mini' });
203
+ const agent = await createAgent({ model, tools: langchainTools });
204
+
205
+ // Natural language requests - LLM decides which tools to use
206
+ const response = await agent.invoke({
207
+ messages: [{
208
+ role: 'user',
209
+ content: 'Create a new contact named John Smith with email john@example.com'
210
+ }]
211
+ });
212
+
213
+ console.log(response.messages[response.messages.length - 1].content);
214
+ ```
215
+
216
+ **Agent Examples:**
217
+ ```
218
+ User: "Create a new contact for John Smith with email john@example.com"
219
+ Agent: "I'll create a new contact with that information..." [calls hubspot-create-contact]
220
+ Agent: "Done! Created contact with ID 123456"
221
+
222
+ User: "Add a new company called TechCorp"
223
+ Agent: "I'll add TechCorp to the system..." [calls hubspot-create-company]
224
+ Agent: "Company TechCorp has been created with ID 789012"
225
+
226
+ User: "How many contacts do we have?"
227
+ Agent: "Let me check..." [calls hubspot-list-contacts]
228
+ Agent: "You have 47 contacts in the system"
229
+
230
+ User: "Create a product called Premium Suite for $299.99"
231
+ Agent: "I'll create that product..." [calls hubspot-create-product]
232
+ Agent: "Product Premium Suite created with ID 345678"
233
+
234
+ User: "Generate an invoice"
235
+ Agent: "I'll create an invoice..." [calls hubspot-create-invoice]
236
+ Agent: "Invoice created with ID 567890"
237
+ ```
238
+
239
+ **File:** [hubspot-langchain.ts](hubspot-langchain.ts)
240
+
241
+ ## šŸ”§ Supported Operations
242
+
243
+ All examples work with these HubSpot operations:
244
+
245
+ | Operation | Tool Name | Example |
246
+ |-----------|-----------|---------|
247
+ | **Create Contact** | `hubspot-create-contact` | Create a new contact |
248
+ | **Get Contact** | `hubspot-get-contact` | Retrieve contact details |
249
+ | **List Contacts** | `hubspot-list-contacts` | List all contacts |
250
+ | **Create Company** | `hubspot-create-company` | Create a new company |
251
+ | **Get Company** | `hubspot-get-company` | Retrieve company details |
252
+ | **Create Product** | `hubspot-create-product` | Create a new product |
253
+ | **Create Invoice** | `hubspot-create-invoice` | Create a new invoice |
254
+ | **List Products** | `hubspot-list-products` | List all products |
255
+
256
+ See [packages/hubspot/README.md](../../packages/hubspot/README.md) for complete tool list and documentation.
257
+
258
+ ## šŸ“– Full Documentation
259
+
260
+ For comprehensive documentation, see:
261
+
262
+ - **Package Docs:** [packages/hubspot/README.md](../../packages/hubspot/README.md)
263
+ - **HubSpot API Reference:** https://developers.hubspot.com/docs/api-reference/crm-objects
264
+ - **Service Keys Guide:** https://developers.hubspot.com/docs/apps/developer-platform/build-apps/authentication/account-service-keys
265
+ - **Matimo Documentation:** [docs/getting-started/](../../docs/getting-started/)
266
+
267
+ ## šŸ› ļø Troubleshooting
268
+
269
+ ### "MATIMO_HUBSPOT_API_KEY not set"
270
+ ```bash
271
+ # Solution: Set your HubSpot service key
272
+ export MATIMO_HUBSPOT_API_KEY="pat-na1-your-key-here"
273
+ ```
274
+
275
+ ### "Property does not exist"
276
+ Your service key might not have the required scopes. Go to HubSpot Settings → Integrations → Service Keys and verify all 14 CRM scopes are enabled.
277
+
278
+ ### "Unauthorized" (401 error)
279
+ - Verify your service key is correct (check for typos)
280
+ - Verify scopes include the required permissions
281
+ - Try rotating the key: Settings → Service Keys → your key → Rotate
282
+
283
+ ### "OpenAI API error" (LangChain example)
284
+ ```bash
285
+ # Solution: Ensure OpenAI API key is set
286
+ export OPENAI_API_KEY="sk-your-openai-key-here"
287
+
288
+ # Get one from: https://platform.openai.com/account/api-keys
289
+ ```
290
+
291
+ ### "Module not found: @langchain/openai"
292
+ ```bash
293
+ # Solution: Install LangChain dependencies
294
+ pnpm install
295
+ ```
296
+
297
+ ## šŸš€ Next Steps
298
+
299
+ 1. **Try each example:**
300
+ - Start with Factory (simplest)
301
+ - Try Decorator (OOP style)
302
+ - Explore LangChain (AI-driven)
303
+
304
+ 2. **Build your own:**
305
+ - Combine patterns as needed
306
+ - Add more HubSpot tools from [full list](../../packages/hubspot/README.md)
307
+ - Integrate with your own application
308
+
309
+ 3. **Advanced:**
310
+ - Use multi-step workflows with LangChain agent
311
+ - Chain multiple HubSpot operations
312
+ - Combine HubSpot tools with other Matimo providers (Slack, Gmail, etc.)
313
+
314
+ ---
315
+
316
+ **Questions?** See [CONTRIBUTING.md](../../CONTRIBUTING.md) or review the Matimo core documentation.
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ============================================================================
4
+ * HUBSPOT TOOLS - DECORATOR PATTERN EXAMPLE
5
+ * ============================================================================
6
+ *
7
+ * PATTERN: Class Decorator Pattern
8
+ * ─────────────────────────────────────────────────────────────────────────
9
+ * Tool execution via @tool decorators - class-based approach.
10
+ *
11
+ * Use this pattern when:
12
+ * āœ… Building agents with class-based structure
13
+ * āœ… Encapsulating tool logic in methods
14
+ * āœ… Integration with LangChain or CrewAI
15
+ * āœ… Domain-specific agent classes
16
+ *
17
+ * SETUP:
18
+ * ─────────────────────────────────────────────────────────────────────────
19
+ * 1. Create .env file:
20
+ * MATIMO_HUBSPOT_API_KEY=pat-na1-xxxxxxxxxxxx
21
+ *
22
+ * 2. Get a Service Key:
23
+ * - Go to: https://app.hubapi.com/settings/integrations/service-keys
24
+ * - Click "Create service key"
25
+ * - Select required scopes
26
+ * - Copy the service key
27
+ *
28
+ * USAGE:
29
+ * ─────────────────────────────────────────────────────────────────────────
30
+ * export MATIMO_HUBSPOT_API_KEY=pat-na1-xxxx
31
+ * npm run hubspot:decorator
32
+ *
33
+ * ============================================================================
34
+ */
35
+
36
+ import 'dotenv/config';
37
+ import { MatimoInstance, setGlobalMatimoInstance, tool } from '@matimo/core';
38
+
39
+ /**
40
+ * Run decorator pattern examples
41
+ */
42
+ async function runDecoratorPatternExamples() {
43
+ console.info('\n╔════════════════════════════════════════════════════════╗');
44
+ console.info('ā•‘ HubSpot Tools - Decorator Pattern ā•‘');
45
+ console.info('ā•‘ (Class-based approach with decorators) ā•‘');
46
+ console.info('ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n');
47
+
48
+ const apiKey = process.env.MATIMO_HUBSPOT_API_KEY;
49
+ if (!apiKey) {
50
+ console.error('āŒ Error: MATIMO_HUBSPOT_API_KEY not set in .env');
51
+ console.error('\nSetup Instructions:');
52
+ console.error('1. Create a Service Key in HubSpot');
53
+ console.error('2. Set environment variable: export MATIMO_HUBSPOT_API_KEY="pat-na1-xxxx"');
54
+ console.error('3. Or create .env: echo "MATIMO_HUBSPOT_API_KEY=pat-na1-xxxx" > .env');
55
+ process.exit(1);
56
+ }
57
+
58
+ console.info(`šŸ”‘ Service Key is set`);
59
+ console.info('šŸš€ Initializing Matimo...\n');
60
+
61
+ // Initialize Matimo with auto-discovery
62
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
63
+
64
+ // Set global instance for decorators
65
+ setGlobalMatimoInstance(matimo);
66
+
67
+ const allTools = matimo.listTools();
68
+ console.info(`āœ… Loaded ${allTools.length} total tools\n`);
69
+
70
+ const hubspotTools = allTools.filter((t) => t.name.startsWith('hubspot-'));
71
+ console.info(`šŸ”§ Found ${hubspotTools.length} HubSpot tools\n`);
72
+
73
+ class HubSpotAgent {
74
+ @tool('hubspot-create-contact')
75
+ async createContact(email: string, firstname?: string, lastname?: string): Promise<unknown> {
76
+ // Decorator auto-executes via matimo
77
+ return undefined;
78
+ }
79
+
80
+ @tool('hubspot-get-contact')
81
+ async getContact(id: string, properties?: string[]): Promise<unknown> {
82
+ // Decorator auto-executes via matimo
83
+ return undefined;
84
+ }
85
+
86
+ @tool('hubspot-create-company')
87
+ async createCompany(name: string, domain?: string): Promise<unknown> {
88
+ // Decorator auto-executes via matimo
89
+ return undefined;
90
+ }
91
+
92
+ @tool('hubspot-list-contacts')
93
+ async listContacts(limit?: number, after?: string, properties?: string[]): Promise<unknown> {
94
+ // Decorator auto-executes via matimo
95
+ return undefined;
96
+ }
97
+
98
+ @tool('hubspot-create-product')
99
+ async createProduct(name: string, description?: string, price?: number): Promise<unknown> {
100
+ // Decorator auto-executes via matimo
101
+ return undefined;
102
+ }
103
+
104
+ @tool('hubspot-create-invoice')
105
+ async createInvoice(hs_currency?: string): Promise<unknown> {
106
+ // Decorator auto-executes via matimo
107
+ return undefined;
108
+ }
109
+ }
110
+
111
+ console.info('════════════════════════════════════════════════════════════\n');
112
+ console.info('Running Decorator Pattern Examples:');
113
+ console.info('════════════════════════════════════════════════════════════\n');
114
+
115
+ try {
116
+ const agent = new HubSpotAgent();
117
+
118
+ // Example 1: Create contact via decorator
119
+ console.info('1ļøāƒ£ Creating contact via decorator...');
120
+ const contact = await agent.createContact(
121
+ `decorator-test-${Date.now()}@example.com`,
122
+ 'Decorator',
123
+ 'Test'
124
+ );
125
+ const contactId = (contact as any).data?.id;
126
+ console.info(` āœ… Contact created: ${contactId}\n`);
127
+
128
+ // Example 2: Get contact via decorator
129
+ if (contactId) {
130
+ console.info('2ļøāƒ£ Retrieving contact via decorator...');
131
+ const contactData = await agent.getContact(contactId, ['email', 'firstname', 'lastname']);
132
+ const props = (contactData as any).data?.properties || {};
133
+ console.info(` āœ… Retrieved contact: ${props.email}\n`);
134
+ }
135
+
136
+ // Example 3: Create company via decorator
137
+ console.info('3ļøāƒ£ Creating company via decorator...');
138
+ const company = await agent.createCompany(`Company ${Date.now()}`, 'example.com');
139
+ const companyId = (company as any).data?.id;
140
+ console.info(` āœ… Company created: ${companyId}\n`);
141
+
142
+ // Example 4: List contacts via decorator
143
+ console.info('4ļøāƒ£ Listing contacts via decorator...');
144
+ const contactsList = await agent.listContacts(5, undefined, ['email', 'firstname', 'lastname']);
145
+ const count = ((contactsList as any).data?.results || []).length;
146
+ console.info(` āœ… Found ${count} contacts\n`);
147
+
148
+ // Example 5: Create product via decorator
149
+ console.info('5ļøāƒ£ Creating product via decorator...');
150
+ const product = await agent.createProduct(
151
+ `Product ${Date.now()}`,
152
+ 'Created via decorator pattern',
153
+ 19999
154
+ );
155
+ const productId = (product as any).data?.id;
156
+ console.info(` āœ… Product created: ${productId}\n`);
157
+
158
+ // Example 6: Create invoice via decorator
159
+ console.info('6ļøāƒ£ Creating invoice via decorator...');
160
+ const invoice = await agent.createInvoice('USD');
161
+ const invoiceId = (invoice as any).data?.id;
162
+ console.info(` āœ… Invoice created: ${invoiceId}\n`);
163
+
164
+ console.info('════════════════════════════════════════════════════════════');
165
+ console.info('✨ Decorator Pattern Example Complete!');
166
+ console.info('════════════════════════════════════════════════════════════\n');
167
+ console.info('Summary of agent actions:');
168
+ console.info(` • Created contact: ${contactId}`);
169
+ console.info(` • Retrieved contact: ${contactId}`);
170
+ console.info(` • Created company: ${companyId}`);
171
+ console.info(` • Found contacts: ${count}`);
172
+ console.info(` • Created product: ${productId}`);
173
+ console.info(` • Created invoice: ${invoiceId}\n`);
174
+ } catch (error) {
175
+ console.error('āŒ Error:', error instanceof Error ? error.message : error);
176
+ process.exit(1);
177
+ }
178
+ }
179
+
180
+ runDecoratorPatternExamples().catch(console.error);
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ============================================================================
4
+ * HUBSPOT TOOLS - FACTORY PATTERN EXAMPLE
5
+ * ============================================================================
6
+ *
7
+ * PATTERN: SDK Factory Pattern
8
+ * ─────────────────────────────────────────────────────────────────────────
9
+ * Direct tool execution via MatimoInstance - the simplest way to use tools.
10
+ *
11
+ * Use this pattern when:
12
+ * āœ… Building simple scripts or CLI tools
13
+ * āœ… Direct API calls without abstraction
14
+ * āœ… Quick prototyping
15
+ * āœ… One-off tool execution
16
+ *
17
+ * SETUP:
18
+ * ─────────────────────────────────────────────────────────────────────────
19
+ * 1. Create .env file:
20
+ * MATIMO_HUBSPOT_API_KEY=pat-na1-xxxxxxxxxxxx
21
+ *
22
+ * 2. Get a Service Key:
23
+ * - Go to: https://app.hubapi.com/settings/integrations/service-keys
24
+ * - Click "Create service key"
25
+ * - Select required scopes (contacts, companies, deals, tickets, etc.)
26
+ * - Copy the service key
27
+ *
28
+ * USAGE:
29
+ * ─────────────────────────────────────────────────────────────────────────
30
+ * export MATIMO_HUBSPOT_API_KEY=pat-na1-xxxx
31
+ * npm run hubspot:factory
32
+ *
33
+ * AVAILABLE TOOLS (50 TOTAL):
34
+ * ─────────────────────────────────────────────────────────────────────────
35
+ * Contacts (5): create, get, update, delete, list
36
+ * Companies (5): create, get, update, delete, list
37
+ * Deals (5): create, get, update, delete, list
38
+ * Tickets (5): create, get, update, delete, list
39
+ * Leads (5): create, get, update, delete, list
40
+ * Line Items (5): create, get, update, delete, list
41
+ * Invoices (5): create, get, update, delete, list
42
+ * Orders (5): create, get, update, delete, list
43
+ * Products (5): create, get, update, delete, list
44
+ * Custom Objects (5): create, get, update, delete, list
45
+ *
46
+ * ============================================================================
47
+ */
48
+
49
+ import 'dotenv/config';
50
+ import { MatimoInstance } from '@matimo/core';
51
+
52
+ /**
53
+ * Run factory pattern examples
54
+ */
55
+ async function runFactoryPatternExamples() {
56
+ console.info('\n╔════════════════════════════════════════════════════════╗');
57
+ console.info('ā•‘ HubSpot Tools - Factory Pattern ā•‘');
58
+ console.info('ā•‘ (Direct execution - simplest approach) ā•‘');
59
+ console.info('ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n');
60
+
61
+ const apiKey = process.env.MATIMO_HUBSPOT_API_KEY;
62
+ if (!apiKey) {
63
+ console.error('āŒ Error: MATIMO_HUBSPOT_API_KEY not set in .env');
64
+ console.error('\nSetup Instructions:');
65
+ console.error('1. Create a Service Key in HubSpot:');
66
+ console.error(' Go to: Settings → Integrations → Service Keys');
67
+ console.error(' Click "Create service key"');
68
+ console.error(' Select all required scopes (contacts, companies, deals, etc.)');
69
+ console.error(' Copy the service key\n');
70
+ console.error('2. Create .env file:');
71
+ console.error(' echo "MATIMO_HUBSPOT_API_KEY=pat-na1-xxxx" > .env\n');
72
+ console.error('3. Or set environment variable:');
73
+ console.error(' export MATIMO_HUBSPOT_API_KEY="pat-na1-xxxx"\n');
74
+ console.error(
75
+ 'šŸ“š Docs: https://developers.hubspot.com/docs/apps/developer-platform/build-apps/authentication/account-service-keys'
76
+ );
77
+ process.exit(1);
78
+ }
79
+
80
+ console.info(`šŸ”‘ Service Key is set`);
81
+ console.info('šŸš€ Initializing Matimo...\n');
82
+
83
+ // Initialize Matimo with auto-discovery to find all @matimo/* packages
84
+ const matimo = await MatimoInstance.init({ autoDiscover: true });
85
+
86
+ const allTools = matimo.listTools();
87
+ console.info(`āœ… Loaded ${allTools.length} total tools\n`);
88
+
89
+ // Get HubSpot tools
90
+ const hubspotTools = allTools.filter((t) => t.name.startsWith('hubspot-'));
91
+ console.info(`šŸ”§ Found ${hubspotTools.length} HubSpot tools`);
92
+ console.info(` - Contacts: 5 tools`);
93
+ console.info(` - Companies: 5 tools`);
94
+ console.info(` - Deals: 5 tools`);
95
+ console.info(` - Tickets: 5 tools`);
96
+ console.info(` - Leads: 5 tools`);
97
+ console.info(` - Line Items: 5 tools`);
98
+ console.info(` - Invoices: 5 tools`);
99
+ console.info(` - Orders: 5 tools`);
100
+ console.info(` - Products: 5 tools`);
101
+ console.info(` - Custom Objects: 5 tools\n`);
102
+
103
+ console.info('════════════════════════════════════════════════════════════\n');
104
+ console.info('Running Examples:');
105
+ console.info('════════════════════════════════════════════════════════════\n');
106
+
107
+ try {
108
+ // Example 1: Create a contact
109
+ console.info('1ļøāƒ£ Creating contact...');
110
+ const createContactResult = await matimo.execute('hubspot-create-contact', {
111
+ email: `factory-test-${Date.now()}@example.com`,
112
+ firstname: 'Factory',
113
+ lastname: 'Test',
114
+ });
115
+ const contactId = (createContactResult as any).data?.id;
116
+ console.info(` āœ… Contact created: ${contactId}\n`);
117
+
118
+ // Example 2: Get the contact
119
+ let contactEmail = '';
120
+ if (contactId) {
121
+ console.info('2ļøāƒ£ Retrieving contact...');
122
+ const getContactResult = await matimo.execute('hubspot-get-contact', {
123
+ id: contactId,
124
+ properties: ['email', 'firstname', 'lastname', 'createdate'],
125
+ });
126
+ const contactData = (getContactResult as any).data?.properties || {};
127
+ contactEmail = contactData.email || '';
128
+ console.info(` āœ… Retrieved contact`);
129
+ console.info(` Email: ${contactData.email}`);
130
+ console.info(` Name: ${contactData.firstname} ${contactData.lastname}`);
131
+ console.info(` Created: ${contactData.createdate}\n`);
132
+ }
133
+
134
+ // Example 3: Create a company
135
+ console.info('3ļøāƒ£ Creating company...');
136
+ const createCompanyResult = await matimo.execute('hubspot-create-company', {
137
+ name: `Test Company ${Date.now()}`,
138
+ domain: 'example.com',
139
+ });
140
+ const companyId = (createCompanyResult as any).data?.id;
141
+ console.info(` āœ… Company created: ${companyId}\n`);
142
+
143
+ // Example 4: List contacts with pagination
144
+ console.info('4ļøāƒ£ Listing contacts (limit 5)...');
145
+ const listContactsResult = await matimo.execute('hubspot-list-contacts', {
146
+ limit: 5,
147
+ properties: ['email', 'firstname', 'lastname'],
148
+ });
149
+ const contactsList = (listContactsResult as any).data?.results || [];
150
+ console.info(` āœ… Found ${contactsList.length} contacts\n`);
151
+
152
+ // Example 5: Create a product
153
+ console.info('5ļøāƒ£ Creating product...');
154
+ const createProductResult = await matimo.execute('hubspot-create-product', {
155
+ name: `Test Product ${Date.now()}`,
156
+ description: 'A sample product for testing',
157
+ price: 9999,
158
+ });
159
+ const productId = (createProductResult as any).data?.id;
160
+ console.info(` āœ… Product created: ${productId}\n`);
161
+
162
+ // Example 6: Create an invoice
163
+ console.info('6ļøāƒ£ Creating invoice...');
164
+ const createInvoiceResult = await matimo.execute('hubspot-create-invoice', {
165
+ hs_currency: 'USD',
166
+ });
167
+ const invoiceId = (createInvoiceResult as any).data?.id;
168
+ console.info(` āœ… Invoice created: ${invoiceId}\n`);
169
+
170
+ console.info('════════════════════════════════════════════════════════════');
171
+ console.info('✨ Factory Pattern Example Complete!');
172
+ console.info('════════════════════════════════════════════════════════════\n');
173
+ console.info('Summary of actions:');
174
+ console.info(` • Created contact: ${contactId}`);
175
+ if (contactEmail) {
176
+ console.info(` • Retrieved contact: ${contactEmail}`);
177
+ }
178
+ console.info(` • Created company: ${companyId}`);
179
+ console.info(` • Listed contacts: ${contactsList.length} found`);
180
+ console.info(` • Created product: ${productId}`);
181
+ console.info(` • Created invoice: ${invoiceId}\n`);
182
+ } catch (error) {
183
+ console.error('āŒ Error:', error instanceof Error ? error.message : error);
184
+ process.exit(1);
185
+ }
186
+ }
187
+
188
+ runFactoryPatternExamples().catch(console.error);