@coffeerunhobby/mcp-ha-connect 2.1.0 → 2.2.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.
Files changed (74) hide show
  1. package/README.md +19 -3
  2. package/dist/config.d.ts +4 -0
  3. package/dist/config.js +6 -0
  4. package/dist/config.js.map +1 -1
  5. package/dist/haClient/automations.d.ts +18 -2
  6. package/dist/haClient/automations.js +25 -7
  7. package/dist/haClient/automations.js.map +1 -1
  8. package/dist/haClient/events.d.ts +60 -7
  9. package/dist/haClient/events.js +252 -47
  10. package/dist/haClient/events.js.map +1 -1
  11. package/dist/haClient/index.d.ts +2 -1
  12. package/dist/haClient/index.js +4 -3
  13. package/dist/haClient/index.js.map +1 -1
  14. package/dist/haClient/wsCommand.d.ts +16 -0
  15. package/dist/haClient/wsCommand.js +36 -0
  16. package/dist/haClient/wsCommand.js.map +1 -0
  17. package/dist/omadaClient/site.js +15 -2
  18. package/dist/omadaClient/site.js.map +1 -1
  19. package/dist/ownerQuestions/service.d.ts +167 -0
  20. package/dist/ownerQuestions/service.js +439 -0
  21. package/dist/ownerQuestions/service.js.map +1 -0
  22. package/dist/server/common.d.ts +3 -0
  23. package/dist/server/common.js +2 -1
  24. package/dist/server/common.js.map +1 -1
  25. package/dist/server/http.js +30 -6
  26. package/dist/server/http.js.map +1 -1
  27. package/dist/server/stream.d.ts +2 -0
  28. package/dist/server/stream.js +2 -1
  29. package/dist/server/stream.js.map +1 -1
  30. package/dist/tools/common.d.ts +1 -1
  31. package/dist/tools/common.js +4 -1
  32. package/dist/tools/common.js.map +1 -1
  33. package/dist/tools/homeassistant/askOwner.d.ts +29 -0
  34. package/dist/tools/homeassistant/askOwner.js +85 -0
  35. package/dist/tools/homeassistant/askOwner.js.map +1 -0
  36. package/dist/tools/homeassistant/getAutomationTrace.d.ts +5 -0
  37. package/dist/tools/homeassistant/getAutomationTrace.js +10 -5
  38. package/dist/tools/homeassistant/getAutomationTrace.js.map +1 -1
  39. package/dist/tools/index.d.ts +3 -0
  40. package/dist/tools/index.js +5 -1
  41. package/dist/tools/index.js.map +1 -1
  42. package/dist/utils/plainText.d.ts +22 -0
  43. package/dist/utils/plainText.js +39 -0
  44. package/dist/utils/plainText.js.map +1 -0
  45. package/dist/version.d.ts +1 -1
  46. package/dist/version.js +1 -1
  47. package/docs/CHANGELOG.md +19 -0
  48. package/openapi.json +1 -1
  49. package/package.json +1 -1
  50. package/src/config.ts +10 -0
  51. package/src/haClient/automations.ts +39 -7
  52. package/src/haClient/events.ts +289 -56
  53. package/src/haClient/index.ts +10 -4
  54. package/src/haClient/wsCommand.ts +44 -0
  55. package/src/omadaClient/site.ts +17 -2
  56. package/src/ownerQuestions/service.ts +536 -0
  57. package/src/server/common.ts +5 -1
  58. package/src/server/http.ts +30 -6
  59. package/src/server/stream.ts +4 -1
  60. package/src/tools/common.ts +4 -1
  61. package/src/tools/homeassistant/askOwner.ts +133 -0
  62. package/src/tools/homeassistant/getAutomationTrace.ts +13 -7
  63. package/src/tools/index.ts +8 -1
  64. package/src/utils/plainText.ts +48 -0
  65. package/src/version.ts +1 -1
  66. package/tests/config.test.ts +12 -0
  67. package/tests/haClient/automationTrace.test.ts +59 -0
  68. package/tests/haClient/automations.test.ts +16 -0
  69. package/tests/haClient/events.test.ts +455 -0
  70. package/tests/haClient/eventsTls.test.ts +52 -0
  71. package/tests/omadaClient/ntp.test.ts +15 -0
  72. package/tests/ownerQuestions/service.test.ts +499 -0
  73. package/tests/ownerQuestions/tools.test.ts +186 -0
  74. package/tests/tools/homeassistant/handlers.test.ts +10 -1
@@ -0,0 +1,186 @@
1
+ /**
2
+ * askOwner / getOwnerAnswer / cancelOwnerQuestion tools: input validation,
3
+ * RBAC, caller binding, log redaction, and a real MCP round trip.
4
+ */
5
+
6
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
7
+ import type { McpServer } from '@modelcontextprotocol/server';
8
+ import { Client, InMemoryTransport } from '@modelcontextprotocol/client';
9
+
10
+ import { OwnerQuestionService } from '../../src/ownerQuestions/service.js';
11
+ import { registerOwnerQuestionTools, askOwnerSchema } from '../../src/tools/homeassistant/askOwner.js';
12
+ import { createServer } from '../../src/server/common.js';
13
+ import { Permission, Role } from '../../src/permissions/index.js';
14
+ import { setLocalFullTrust } from '../../src/tools/common.js';
15
+ import { logger } from '../../src/utils/logger.js';
16
+
17
+ type Handler = (args: unknown, extra: unknown) => Promise<{ content: { text: string }[]; isError?: boolean }>;
18
+
19
+ function createMockServer() {
20
+ const handlers = new Map<string, Handler>();
21
+ return {
22
+ registerTool: vi.fn((name: string, _config: unknown, handler: Handler) => handlers.set(name, handler)),
23
+ handlers,
24
+ } as unknown as McpServer & { handlers: Map<string, Handler> };
25
+ }
26
+
27
+ const extraFor = (sub: string, permissions: number) => ({
28
+ sessionId: 's',
29
+ http: { authInfo: { token: '', clientId: sub, scopes: [], extra: { permissions } } },
30
+ });
31
+
32
+ const parse = (result: { content: { text: string }[] }) => JSON.parse(result.content[0].text) as Record<string, unknown>;
33
+
34
+ const valid = { question: 'Aprinzi lumina în baie?', target: 'mobile_app_phone_user5' };
35
+
36
+ function makeService() {
37
+ const notify = vi.fn().mockResolvedValue([]);
38
+ const service = new OwnerQuestionService({ notify, subscribe: vi.fn().mockResolvedValue('s'), secret: 'k'.repeat(40) });
39
+ return { service, notify };
40
+ }
41
+
42
+ describe('askOwner input validation', () => {
43
+ it('accepts plain text including Romanian diacritics, and applies defaults', () => {
44
+ const parsed = askOwnerSchema.parse(valid);
45
+ expect(parsed.question).toBe('Aprinzi lumina în baie?');
46
+ expect(parsed.buttons).toBeUndefined();
47
+ });
48
+
49
+ it('NFC-normalizes text (a decomposed ș becomes one character)', () => {
50
+ expect(askOwnerSchema.parse({ ...valid, question: 'ș?' }).question).toBe('ș?');
51
+ });
52
+
53
+ it.each([
54
+ ['an emoji', { question: 'Approve? 👍' }, /U\+1F44D/],
55
+ ['a zero-width joiner', { question: 'ok‍ok' }, /U\+200D/],
56
+ ['a right-to-left override', { question: 'pay ‮evil' }, /U\+202E/],
57
+ ['stacked combining marks', { question: 'á́' }, /U\+0301/],
58
+ ['a 257-character question', { question: 'x'.repeat(257) }, /257 characters; the maximum is 256/],
59
+ ['a line break in the title', { title: 'two\nlines' }, /title contains a disallowed character U\+000A/],
60
+ ['a 61-character title', { title: 't'.repeat(61) }, /maximum is 60/],
61
+ ['an emoji button', { buttons: ['Yes ✅', 'No'] }, /button label/],
62
+ ['four buttons', { buttons: ['a', 'b', 'c', 'd'] }, /3/],
63
+ ['duplicate buttons', { buttons: ['Yes', 'yes'] }, /unique/],
64
+ ['a non-mobile target', { target: 'persistent_notification' }, /mobile app notify service/],
65
+ ['a timeout over 7 days', { timeoutSeconds: 7 * 24 * 3600 + 1 }, /604800/],
66
+ ['a timeout under a minute', { timeoutSeconds: 59 }, /60/],
67
+ ])('refuses %s', (_name, overrides, error) => {
68
+ const result = askOwnerSchema.safeParse({ ...valid, ...overrides });
69
+ expect(result.success).toBe(false);
70
+ expect(JSON.stringify(result.error!.issues)).toMatch(error);
71
+ });
72
+
73
+ it('accepts a 256-character question with line breaks', () => {
74
+ const question = `${'x'.repeat(100)}\n${'y'.repeat(155)}`;
75
+ expect(askOwnerSchema.parse({ ...valid, question }).question).toBe(question);
76
+ });
77
+ });
78
+
79
+ describe('owner question tools', () => {
80
+ let server: ReturnType<typeof createMockServer>;
81
+ let service: OwnerQuestionService;
82
+ let notify: ReturnType<typeof vi.fn>;
83
+
84
+ beforeEach(() => {
85
+ server = createMockServer();
86
+ ({ service, notify } = makeService());
87
+ registerOwnerQuestionTools(server, service);
88
+ });
89
+
90
+ it('registers askOwner, getOwnerAnswer and cancelOwnerQuestion', () => {
91
+ expect([...server.handlers.keys()]).toEqual(['askOwner', 'getOwnerAnswer', 'cancelOwnerQuestion']);
92
+ });
93
+
94
+ it.each(['askOwner', 'getOwnerAnswer', 'cancelOwnerQuestion'])('%s requires NOTIFY', async (tool) => {
95
+ const result = await server.handlers.get(tool)!({ ...valid, requestId: 'x' }, extraFor('reader', Role.READONLY));
96
+ expect(parse(result)).toMatchObject({ error: 'Permission denied' });
97
+ expect(String(parse(result).message)).toContain('NOTIFY');
98
+ expect(notify).not.toHaveBeenCalled();
99
+ });
100
+
101
+ it('askOwner applies the default title, buttons and timeout', async () => {
102
+ const result = await server.handlers.get('askOwner')!(valid, extraFor('approver', Permission.NOTIFY));
103
+
104
+ expect(parse(result)).toHaveProperty('requestId');
105
+ expect(notify.mock.calls[0][1]).toMatchObject({ title: 'Approval needed', data: { timeout: 600 } });
106
+ expect(notify.mock.calls[0][1].data.actions.map((a: { title: string }) => a.title)).toEqual(['Approve', 'Deny']);
107
+ });
108
+
109
+ it('binds the question to the asking token sub', async () => {
110
+ const asked = parse(await server.handlers.get('askOwner')!(valid, extraFor('approver', Permission.NOTIFY)));
111
+
112
+ const own = await server.handlers.get('getOwnerAnswer')!({ requestId: asked.requestId, waitSeconds: 0 }, extraFor('approver', Permission.NOTIFY));
113
+ const other = await server.handlers.get('getOwnerAnswer')!({ requestId: asked.requestId, waitSeconds: 0 }, extraFor('harvey', Permission.NOTIFY));
114
+
115
+ expect(parse(own)).toMatchObject({ status: 'pending' });
116
+ expect(other.isError).toBe(true);
117
+ expect(String(parse(other).message)).toMatch(/different client/);
118
+ });
119
+
120
+ it('logs tool arguments (the question text) at debug level only', async () => {
121
+ const info = vi.spyOn(logger, 'info');
122
+ const debug = vi.spyOn(logger, 'debug');
123
+ try {
124
+ await server.handlers.get('askOwner')!(
125
+ { ...valid, question: 'Secret plan: unlock the front door?' },
126
+ extraFor('approver', Permission.NOTIFY)
127
+ );
128
+ expect(JSON.stringify(info.mock.calls)).not.toContain('unlock the front door');
129
+ expect(JSON.stringify(info.mock.calls)).toContain('Tool invoked');
130
+ expect(JSON.stringify(debug.mock.calls)).toContain('unlock the front door');
131
+ } finally {
132
+ info.mockRestore();
133
+ debug.mockRestore();
134
+ }
135
+ });
136
+ });
137
+
138
+ describe('owner question tools over MCP', () => {
139
+ beforeEach(() => setLocalFullTrust(true));
140
+ afterEach(() => setLocalFullTrust(false));
141
+
142
+ it('are listed with a JSON Schema and callable end to end', async () => {
143
+ const { service, notify } = makeService();
144
+ const server = createServer({ haClient: {} as never, ownerQuestions: service });
145
+ const client = new Client({ name: 'ask-owner-test', version: '0' });
146
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
147
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
148
+ try {
149
+ const { tools } = await client.listTools();
150
+ const askOwner = tools.find((t) => t.name === 'askOwner');
151
+ expect(askOwner?.inputSchema.required).toEqual(['question', 'target']);
152
+ expect(tools.map((t) => t.name)).toEqual(expect.arrayContaining(['getOwnerAnswer', 'cancelOwnerQuestion']));
153
+
154
+ const asked = await client.callTool({ name: 'askOwner', arguments: { ...valid, buttons: ['Da', 'Nu'] } });
155
+ const { requestId } = JSON.parse((asked.content as Array<{ text: string }>)[0].text);
156
+ expect(notify).toHaveBeenCalledTimes(1);
157
+
158
+ const answer = await client.callTool({ name: 'getOwnerAnswer', arguments: { requestId, waitSeconds: 0 } });
159
+ expect(JSON.parse((answer.content as Array<{ text: string }>)[0].text)).toMatchObject({
160
+ status: 'pending',
161
+ buttons: ['Da', 'Nu'],
162
+ });
163
+
164
+ const refused = await client.callTool({ name: 'askOwner', arguments: { ...valid, question: 'ok 👍' } });
165
+ expect(refused.isError).toBe(true);
166
+ expect(notify).toHaveBeenCalledTimes(1);
167
+ } finally {
168
+ await client.close();
169
+ await server.close();
170
+ }
171
+ });
172
+
173
+ it('are not registered when no owner question service is running', async () => {
174
+ const server = createServer({ haClient: {} as never });
175
+ const client = new Client({ name: 'ask-owner-test', version: '0' });
176
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
177
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
178
+ try {
179
+ const { tools } = await client.listTools();
180
+ expect(tools.map((t) => t.name)).not.toContain('askOwner');
181
+ } finally {
182
+ await client.close();
183
+ await server.close();
184
+ }
185
+ });
186
+ });
@@ -551,9 +551,18 @@ describe('HomeAssistant Tool Handlers', () => {
551
551
  const handler = server.getHandler('getAutomationTrace')!;
552
552
  const result = await handler({ entity_id: 'automation.test' }, mockExtra);
553
553
 
554
- expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test');
554
+ expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test', undefined);
555
555
  expect(result.content[0].text).toContain('trace_count');
556
556
  });
557
+
558
+ it('getAutomationTrace forwards limit', async () => {
559
+ mockClient.getAutomationTrace.mockResolvedValue([]);
560
+ registerGetAutomationTraceTool(server as any, mockClient as any);
561
+
562
+ await server.getHandler('getAutomationTrace')!({ entity_id: 'automation.test', limit: 3 }, mockExtra);
563
+
564
+ expect(mockClient.getAutomationTrace).toHaveBeenCalledWith('automation.test', 3);
565
+ });
557
566
  });
558
567
 
559
568
  describe('automation controls', () => {