node-wire-slack 1.1.0__py3-none-any.whl

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.
@@ -0,0 +1,6 @@
1
+ #
2
+ # SPDX-FileCopyrightText: 2026 AOT Technologies
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+
6
+ # Connector subpackage: slack
@@ -0,0 +1,32 @@
1
+ #
2
+ # SPDX-FileCopyrightText: 2026 AOT Technologies
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ """
6
+ Domain exception hierarchy for the Slack connector.
7
+
8
+ These exceptions are raised by logic.py and mapped to ErrorCategory codes via
9
+ logic.py's error_map, scoped to connector_id="slack" by ErrorMapper.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+
15
+ class SlackAuthError(Exception):
16
+ """Raised when the bot token is invalid, revoked, or the account is inactive."""
17
+
18
+
19
+ class SlackPermissionError(Exception):
20
+ """Raised when the token lacks the required OAuth scope for the operation."""
21
+
22
+
23
+ class SlackRateLimitError(Exception):
24
+ """Raised on HTTP 429 or Slack's `ratelimited` error — eligible for retry."""
25
+
26
+
27
+ class SlackUploadError(Exception):
28
+ """Raised when a file upload step fails (bad content, missing fields, Slack error)."""
29
+
30
+
31
+ class SlackMessageError(Exception):
32
+ """Raised when a chat.postMessage call fails for a business-logic reason."""
@@ -0,0 +1,513 @@
1
+ #
2
+ # SPDX-FileCopyrightText: 2026 AOT Technologies
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ """
6
+ Slack connector for Node-Wire.
7
+
8
+ Structure mirrors node_wire_smtp/logic.py:
9
+ - Private async HTTP helpers at module level (no separate helper file).
10
+ - SlackConnector(BaseConnector) with one @sdk_action per operation.
11
+
12
+ The Slack Bot Token is NEVER logged or included in exceptions.
13
+ All credentials are resolved at call-time via SecretProvider.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import binascii
20
+ import json
21
+ import logging
22
+ import os
23
+ import re
24
+ from typing import Any, ClassVar, Dict, Tuple, Type
25
+
26
+ import httpx
27
+
28
+ from node_wire_runtime import BaseConnector, ErrorCategory, sdk_action
29
+
30
+ from .exceptions import (
31
+ SlackAuthError,
32
+ SlackMessageError,
33
+ SlackPermissionError,
34
+ SlackRateLimitError,
35
+ SlackUploadError,
36
+ )
37
+ from .schema import (
38
+ SlackOutput,
39
+ SlackPostMessageInput,
40
+ SlackSendDirectMessageInput,
41
+ SlackUploadFileInput,
42
+ )
43
+
44
+ logger = logging.getLogger("connectors.slack")
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # Constants
48
+ # ---------------------------------------------------------------------------
49
+
50
+ _CHAT_POST_URL = "https://slack.com/api/chat.postMessage"
51
+ _GET_UPLOAD_URL = "https://slack.com/api/files.getUploadURLExternal"
52
+ _COMPLETE_UPLOAD_URL = "https://slack.com/api/files.completeUploadExternal"
53
+
54
+ # Configurable for consistency with other connectors (NW_TIMEOUT); NW_SLACK_TIMEOUT
55
+ # takes precedence when set.
56
+ _DEFAULT_TIMEOUT = float(os.getenv("NW_SLACK_TIMEOUT", os.getenv("NW_TIMEOUT", "30.0")))
57
+ _HARD_UPLOAD_LIMIT_MB = 100
58
+ _DEFAULT_UPLOAD_LIMIT_MB = 50
59
+ _CHANNEL_ID_RE = re.compile(r"^[CGDZ][A-Z0-9]{8,}$")
60
+
61
+
62
+ def _get_api_url(path: str) -> str:
63
+ """Helper to construct Slack API URLs, allowing base URL override via NW_SLACK_API_BASE_URL."""
64
+ base = os.environ.get("NW_SLACK_API_BASE_URL", "https://slack.com/api").rstrip("/")
65
+ return f"{base}/{path.lstrip('/')}"
66
+
67
+
68
+ _CHAT_POST_URL = _get_api_url("chat.postMessage")
69
+ _GET_UPLOAD_URL = _get_api_url("files.getUploadURLExternal")
70
+ _COMPLETE_UPLOAD_URL = _get_api_url("files.completeUploadExternal")
71
+
72
+ # Sandboxed directory for filesystem-based uploads.
73
+ _ATTACHMENTS_DIR = os.environ.get("NW_SLACK_ATTACHMENTS_DIR", "/slack_attachments")
74
+
75
+ # Slack error strings that map to specific domain exceptions.
76
+ _AUTH_ERRORS = frozenset({"invalid_auth", "token_revoked", "account_inactive", "not_authed"})
77
+ _SCOPE_ERRORS = frozenset({"missing_scope", "invalid_scopes"})
78
+ _RATE_ERRORS = frozenset({"ratelimited"})
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Private HTTP helpers (module-level, not a separate file)
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def _auth_headers(token: str) -> dict[str, str]:
87
+ return {"Authorization": f"Bearer {token}"}
88
+
89
+
90
+ def _is_valid_channel_id(value: str) -> bool:
91
+ """Return True when *value* matches Slack's channel_id format."""
92
+ return bool(_CHANNEL_ID_RE.fullmatch(value.strip()))
93
+
94
+
95
+ def _raise_for_slack_error(response_json: dict[str, Any], http_status: int) -> None:
96
+ """Translate a Slack `ok: false` payload into a typed domain exception."""
97
+ slack_error = response_json.get("error", "unknown")
98
+ messages = response_json.get("response_metadata", {}).get("messages", [])
99
+ detail = ". ".join(messages) if messages else str(slack_error)
100
+
101
+ logger.error(
102
+ "Slack API error '%s': %s",
103
+ slack_error,
104
+ detail,
105
+ extra={"connector_id": "slack"},
106
+ )
107
+ if slack_error in _AUTH_ERRORS:
108
+ raise SlackAuthError("Slack authentication failed or token was revoked.")
109
+ if slack_error in _SCOPE_ERRORS:
110
+ raise SlackPermissionError(f"Slack permission error: {detail}")
111
+ if slack_error in _RATE_ERRORS or http_status == 429:
112
+ raise SlackRateLimitError(f"Slack rate limit: {detail}")
113
+ raise SlackMessageError(f"Slack API error '{slack_error}': {detail}")
114
+
115
+
116
+ async def _post_json(
117
+ url: str,
118
+ token: str,
119
+ body: dict[str, Any],
120
+ timeout: float = _DEFAULT_TIMEOUT,
121
+ ) -> dict[str, Any]:
122
+ """POST JSON to the Slack API. Raises a typed exception on failure."""
123
+ async with httpx.AsyncClient(timeout=timeout) as client:
124
+ response = await client.post(
125
+ url,
126
+ headers={**_auth_headers(token), "Content-Type": "application/json"},
127
+ json=body,
128
+ )
129
+ data = response.json()
130
+ if not data.get("ok"):
131
+ _raise_for_slack_error(data, response.status_code)
132
+ return data
133
+
134
+
135
+ async def _get_upload_url(
136
+ token: str,
137
+ filename: str,
138
+ length: int,
139
+ timeout: float = _DEFAULT_TIMEOUT,
140
+ ) -> tuple[str, str]:
141
+ """Step 1 of the external upload flow. Returns (upload_url, file_id)."""
142
+ async with httpx.AsyncClient(timeout=timeout) as client:
143
+ response = await client.post(
144
+ _GET_UPLOAD_URL,
145
+ headers=_auth_headers(token),
146
+ data={"filename": filename, "length": str(length)},
147
+ )
148
+ data = response.json()
149
+ if not data.get("ok"):
150
+ _raise_for_slack_error(data, response.status_code)
151
+ upload_url = data.get("upload_url", "")
152
+ file_id = data.get("file_id", "")
153
+ if not upload_url or not file_id:
154
+ raise SlackUploadError("Slack did not return upload_url or file_id.")
155
+ return upload_url, file_id
156
+
157
+
158
+ async def _upload_bytes(
159
+ upload_url: str,
160
+ content: bytes,
161
+ timeout: float = _DEFAULT_TIMEOUT,
162
+ ) -> None:
163
+ """Step 2: PUT raw bytes to the pre-signed URL Slack returned."""
164
+ async with httpx.AsyncClient(timeout=timeout) as client:
165
+ response = await client.post(
166
+ upload_url,
167
+ content=content,
168
+ headers={"Content-Type": "application/octet-stream"},
169
+ )
170
+ if response.status_code != 200:
171
+ raise SlackUploadError(f"Upload to pre-signed URL failed with HTTP {response.status_code}.")
172
+
173
+
174
+ async def _complete_upload(
175
+ token: str,
176
+ file_id: str,
177
+ title: str,
178
+ channel_id: str = "",
179
+ initial_comment: str = "",
180
+ timeout: float = _DEFAULT_TIMEOUT,
181
+ ) -> dict[str, Any]:
182
+ """Step 3: Finalise the upload and optionally share to a channel."""
183
+ data: dict[str, Any] = {
184
+ "files": json.dumps([{"id": file_id, "title": title}]),
185
+ }
186
+ if _is_valid_channel_id(channel_id):
187
+ data["channel_id"] = channel_id
188
+ if initial_comment:
189
+ data["initial_comment"] = initial_comment
190
+
191
+ async with httpx.AsyncClient(timeout=timeout) as client:
192
+ response = await client.post(
193
+ _COMPLETE_UPLOAD_URL,
194
+ headers=_auth_headers(token),
195
+ data=data,
196
+ )
197
+ resp_data = response.json()
198
+ if not resp_data.get("ok"):
199
+ _raise_for_slack_error(resp_data, response.status_code)
200
+ return resp_data
201
+
202
+
203
+ def _resolve_blocks(blocks: Any) -> list[Any] | None:
204
+ """Parse Block Kit payload from a JSON string or pass through a list.
205
+ Raises SlackMessageError on invalid JSON."""
206
+ if blocks is None:
207
+ return None
208
+ if isinstance(blocks, list):
209
+ return blocks
210
+ if isinstance(blocks, str) and blocks.strip():
211
+ try:
212
+ parsed = json.loads(blocks)
213
+ except (json.JSONDecodeError, TypeError) as exc:
214
+ raise SlackMessageError(f"Invalid blocks JSON: {exc}") from exc
215
+ if not isinstance(parsed, list):
216
+ raise SlackMessageError("blocks must be a JSON array.")
217
+ return parsed
218
+ return None
219
+
220
+
221
+ def _get_upload_limit_bytes() -> int:
222
+ raw = os.environ.get("NW_SLACK_UPLOAD_LIMIT_MB", "")
223
+ try:
224
+ mb = int(raw.strip()) if raw.strip() else _DEFAULT_UPLOAD_LIMIT_MB
225
+ except ValueError:
226
+ mb = _DEFAULT_UPLOAD_LIMIT_MB
227
+ mb = max(1, min(mb, _HARD_UPLOAD_LIMIT_MB))
228
+ return mb * 1024 * 1024
229
+
230
+
231
+ def _resolve_upload_path(filepath: str) -> str:
232
+ """Validate that *filepath* is under the sandboxed attachments directory."""
233
+ allowed = os.path.realpath(_ATTACHMENTS_DIR)
234
+ if not os.path.isabs(filepath):
235
+ raise SlackUploadError(
236
+ f"filepath must be an absolute path under '{allowed}'. Got: {filepath!r}"
237
+ )
238
+ candidate = os.path.realpath(filepath)
239
+ if candidate != allowed and not candidate.startswith(allowed + os.sep):
240
+ raise SlackUploadError(f"filepath must be under '{allowed}'. Got: {filepath!r}")
241
+ return candidate
242
+
243
+
244
+ async def _resolve_channel_id(token: str, target: str) -> str:
245
+ """
246
+ Resolve a target (Channel name, Channel ID, or User ID) to a Slack Channel ID.
247
+ - If NW_SLACK_SKIP_RESOLVE=true, returns target as-is (useful for mocks/restricted envs).
248
+ - If it already looks like a Channel ID (C, G, D), return it.
249
+ - If it starts with U or W, it's a User ID; call conversations.open to get the DM channel.
250
+ - Otherwise, return as-is (names like #general are handled natively by chat.postMessage).
251
+ """
252
+ target = target.strip()
253
+ if not target:
254
+ return target
255
+
256
+ if os.environ.get("NW_SLACK_SKIP_RESOLVE", "").lower() == "true":
257
+ logger.debug("Skipping channel resolution for %s (NW_SLACK_SKIP_RESOLVE=true)", target)
258
+ return target
259
+
260
+ prefix = target[0].upper()
261
+
262
+ # Already a channel/group/dm ID
263
+ if prefix in ("C", "G", "D", "Z"):
264
+ return target
265
+
266
+ # User ID -> Resolve to DM channel
267
+ if prefix in ("U", "W"):
268
+ try:
269
+ async with httpx.AsyncClient(timeout=_DEFAULT_TIMEOUT) as client:
270
+ response = await client.post(
271
+ _get_api_url("conversations.open"),
272
+ headers={
273
+ "Authorization": f"Bearer {token}",
274
+ "Content-Type": "application/json",
275
+ },
276
+ json={"users": target},
277
+ )
278
+ data = response.json()
279
+ if data.get("ok"):
280
+ resolved_id = data["channel"]["id"]
281
+ logger.debug("Resolved User ID %s to DM channel %s", target, resolved_id)
282
+ return resolved_id
283
+
284
+ # If Slack returns ok: false, fallback to the original ID
285
+ logger.warning(
286
+ "Failed to resolve User ID %s to DM channel: %s", target, data.get("error")
287
+ )
288
+ return target
289
+ except Exception as exc:
290
+ # Catch network errors (ConnectError, etc.) and fallback to original ID
291
+ logger.warning(
292
+ "Network error resolving User ID %s to DM channel; falling back to original",
293
+ target,
294
+ extra={"error_type": type(exc).__name__, "error_message": str(exc)},
295
+ )
296
+ return target
297
+
298
+ return target
299
+
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # Connector
303
+ # ---------------------------------------------------------------------------
304
+
305
+
306
+ class SlackConnector(BaseConnector):
307
+ """
308
+ Slack connector: post messages, send DMs, and upload files to Slack channels.
309
+
310
+ Authentication uses a Slack Bot Token (xoxb-…) fetched at call-time via
311
+ SecretProvider. The token is never stored on the instance or emitted in logs.
312
+
313
+ Actions
314
+ -------
315
+ post_message — chat.postMessage to a channel
316
+ send_direct_message — chat.postMessage to a user DM (same API, by user ID)
317
+ upload_file — 3-step external upload (getUploadURLExternal flow)
318
+ """
319
+
320
+ connector_id = "slack"
321
+ output_model = SlackOutput
322
+
323
+ # Scoped to slack only.
324
+ error_map: ClassVar[Dict[Type[BaseException], Tuple[ErrorCategory, str]]] = {
325
+ SlackAuthError: (ErrorCategory.AUTH, "SLACK_AUTH_ERROR"),
326
+ SlackPermissionError: (ErrorCategory.AUTH, "SLACK_PERMISSION_ERROR"),
327
+ SlackRateLimitError: (ErrorCategory.RETRYABLE, "SLACK_RATE_LIMIT"),
328
+ SlackUploadError: (ErrorCategory.BUSINESS, "SLACK_UPLOAD_ERROR"),
329
+ SlackMessageError: (ErrorCategory.BUSINESS, "SLACK_MESSAGE_ERROR"),
330
+ }
331
+
332
+ # ------------------------------------------------------------------
333
+ # post_message
334
+ # ------------------------------------------------------------------
335
+
336
+ @sdk_action("post_message")
337
+ async def post_message(self, params: SlackPostMessageInput, *, trace_id: str) -> SlackOutput:
338
+ logger.info(
339
+ "Sending Slack channel message",
340
+ extra={
341
+ "trace_id": trace_id,
342
+ "connector_id": self.connector_id,
343
+ "action": "post_message",
344
+ "channel": params.channel,
345
+ },
346
+ )
347
+ token = self.secret_provider.get_secret(params.token_secret_key)
348
+ channel_id = await _resolve_channel_id(token, params.channel)
349
+
350
+ body: dict[str, Any] = {"channel": channel_id, "text": params.message}
351
+ parsed_blocks = _resolve_blocks(params.blocks)
352
+ if parsed_blocks is not None:
353
+ body["blocks"] = parsed_blocks
354
+
355
+ data = await _post_json(_CHAT_POST_URL, token, body)
356
+
357
+ logger.info(
358
+ "Slack channel message sent",
359
+ extra={
360
+ "trace_id": trace_id,
361
+ "connector_id": self.connector_id,
362
+ "action": "post_message",
363
+ "channel": channel_id,
364
+ "ts": data.get("ts"),
365
+ },
366
+ )
367
+ return SlackOutput(
368
+ ok=True,
369
+ ts=data.get("ts"),
370
+ channel=data.get("channel") or channel_id,
371
+ description=f"Message sent to {params.channel}.",
372
+ raw=data,
373
+ )
374
+
375
+ # ------------------------------------------------------------------
376
+ # send_direct_message
377
+ # ------------------------------------------------------------------
378
+
379
+ @sdk_action("send_direct_message")
380
+ async def send_direct_message(
381
+ self, params: SlackSendDirectMessageInput, *, trace_id: str
382
+ ) -> SlackOutput:
383
+ logger.info(
384
+ "Sending Slack direct message",
385
+ extra={
386
+ "trace_id": trace_id,
387
+ "connector_id": self.connector_id,
388
+ "action": "send_direct_message",
389
+ "channel": params.channel,
390
+ },
391
+ )
392
+ token = self.secret_provider.get_secret(params.token_secret_key)
393
+ channel_id = await _resolve_channel_id(token, params.channel)
394
+
395
+ body: dict[str, Any] = {"channel": channel_id, "text": params.message}
396
+ parsed_blocks = _resolve_blocks(params.blocks)
397
+ if parsed_blocks is not None:
398
+ body["blocks"] = parsed_blocks
399
+
400
+ data = await _post_json(_CHAT_POST_URL, token, body)
401
+
402
+ logger.info(
403
+ "Slack direct message sent",
404
+ extra={
405
+ "trace_id": trace_id,
406
+ "connector_id": self.connector_id,
407
+ "action": "send_direct_message",
408
+ "channel": channel_id,
409
+ "ts": data.get("ts"),
410
+ },
411
+ )
412
+ return SlackOutput(
413
+ ok=True,
414
+ ts=data.get("ts"),
415
+ channel=data.get("channel") or channel_id,
416
+ description=f"Direct message sent to user {params.channel}.",
417
+ raw=data,
418
+ )
419
+
420
+ # ------------------------------------------------------------------
421
+ # upload_file
422
+ # ------------------------------------------------------------------
423
+
424
+ @sdk_action("upload_file")
425
+ async def upload_file(self, params: SlackUploadFileInput, *, trace_id: str) -> SlackOutput:
426
+ logger.info(
427
+ "Starting Slack file upload",
428
+ extra={
429
+ "trace_id": trace_id,
430
+ "connector_id": self.connector_id,
431
+ "action": "upload_file",
432
+ "channel": params.channel,
433
+ },
434
+ )
435
+ token = self.secret_provider.get_secret(params.token_secret_key)
436
+ channel_id = await _resolve_channel_id(token, params.channel)
437
+ if params.channel and not _is_valid_channel_id(channel_id):
438
+ raise SlackUploadError(
439
+ f"Could not resolve {params.channel!r} to a valid Slack channel ID. "
440
+ "Provide a channel ID (for example C01AB2CD3EF) instead of a channel name."
441
+ )
442
+ limit_bytes = _get_upload_limit_bytes()
443
+
444
+ # --- Resolve content bytes ---
445
+ if params.filepath:
446
+ safe_path = _resolve_upload_path(params.filepath)
447
+ if not os.path.isfile(safe_path):
448
+ raise SlackUploadError(f"No such file in upload directory: {params.filepath!r}")
449
+ size = os.path.getsize(safe_path)
450
+ effective_filename = params.filename or os.path.basename(safe_path)
451
+ if size > limit_bytes:
452
+ raise SlackUploadError(
453
+ f"File '{effective_filename}' is {size / 1024 / 1024:.2f} MB, "
454
+ f"exceeds limit of {limit_bytes / 1024 / 1024:.0f} MB."
455
+ )
456
+ with open(safe_path, "rb") as fh:
457
+ content_bytes = fh.read()
458
+
459
+ elif params.content_base64:
460
+ effective_filename = params.filename or "upload.bin"
461
+ try:
462
+ content_bytes = base64.b64decode(params.content_base64, validate=True)
463
+ except binascii.Error as exc:
464
+ raise SlackUploadError(f"Invalid base64 content: {exc}") from exc
465
+ if len(content_bytes) > limit_bytes:
466
+ raise SlackUploadError(
467
+ f"Decoded content is {len(content_bytes) / 1024 / 1024:.2f} MB, "
468
+ f"exceeds limit of {limit_bytes / 1024 / 1024:.0f} MB."
469
+ )
470
+
471
+ else:
472
+ raise SlackUploadError("Either 'filepath' or 'content_base64' must be provided.")
473
+
474
+ # --- 3-step external upload ---
475
+ logger.info(
476
+ "Requesting upload URL from Slack",
477
+ extra={
478
+ "trace_id": trace_id,
479
+ "connector_id": self.connector_id,
480
+ "action": "upload_file",
481
+ "nw_filename": effective_filename,
482
+ "size_bytes": len(content_bytes),
483
+ },
484
+ )
485
+ upload_url, file_id = await _get_upload_url(token, effective_filename, len(content_bytes))
486
+
487
+ await _upload_bytes(upload_url, content_bytes)
488
+
489
+ data = await _complete_upload(
490
+ token,
491
+ file_id,
492
+ title=effective_filename,
493
+ channel_id=channel_id,
494
+ initial_comment=params.initial_comment,
495
+ )
496
+
497
+ logger.info(
498
+ "Slack file upload completed",
499
+ extra={
500
+ "trace_id": trace_id,
501
+ "connector_id": self.connector_id,
502
+ "action": "upload_file",
503
+ "channel": channel_id,
504
+ "file_id": file_id,
505
+ },
506
+ )
507
+ return SlackOutput(
508
+ ok=True,
509
+ file_id=file_id,
510
+ channel=params.channel,
511
+ description=f"File '{effective_filename}' uploaded to {params.channel}.",
512
+ raw=data,
513
+ )
@@ -0,0 +1,124 @@
1
+ #
2
+ # SPDX-FileCopyrightText: 2026 AOT Technologies
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ """
6
+ Pydantic v2 input/output models for the Slack connector.
7
+
8
+ All input models include an `action` discriminator field so that
9
+ BaseConnector can build a discriminated union and route to the correct
10
+ @sdk_action method automatically — the same pattern used by Google Drive.
11
+
12
+ Only `channel` and `message` are required for messaging actions.
13
+ Authentication is handled via SecretProvider (never hard-coded here).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any, Dict, List, Literal, Optional, Union
19
+
20
+ from pydantic import BaseModel, ConfigDict, Field
21
+
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Shared input base
25
+ # ---------------------------------------------------------------------------
26
+
27
+
28
+ class _BaseSlackInput(BaseModel):
29
+ """Fields shared by every Slack input model."""
30
+
31
+ model_config = ConfigDict(extra="forbid")
32
+
33
+ token_secret_key: str = Field(
34
+ default="SLACK_BOT_TOKEN",
35
+ description=(
36
+ "SecretProvider key that holds the Slack Bot Token (xoxb-…). "
37
+ "Override only when running multiple bots."
38
+ ),
39
+ )
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Action: post_message
44
+ # ---------------------------------------------------------------------------
45
+
46
+
47
+ class SlackPostMessageInput(_BaseSlackInput):
48
+ """Send a message to a Slack channel."""
49
+
50
+ action: Literal["post_message"] = "post_message"
51
+ channel: str = Field(
52
+ ..., description="Target Channel ID (C…), Name (#general), or User ID (U…)."
53
+ )
54
+ message: str = Field(..., description="Plain-text fallback message (markdown supported).")
55
+ blocks: Optional[Union[str, List[Any]]] = Field(
56
+ default=None,
57
+ description="Block Kit payload as a JSON string or a pre-parsed list.",
58
+ )
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Action: send_direct_message
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ class SlackSendDirectMessageInput(_BaseSlackInput):
67
+ """Send a direct message to a Slack user."""
68
+
69
+ action: Literal["send_direct_message"] = "send_direct_message"
70
+ channel: str = Field(
71
+ ..., description="Target User ID (U…), Channel ID (C…), or Name (#general)."
72
+ )
73
+ message: str = Field(..., description="Plain-text fallback message (markdown supported).")
74
+ blocks: Optional[Union[str, List[Any]]] = Field(
75
+ default=None,
76
+ description="Block Kit payload as a JSON string or a pre-parsed list.",
77
+ )
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # Action: upload_file
82
+ # ---------------------------------------------------------------------------
83
+
84
+
85
+ class SlackUploadFileInput(_BaseSlackInput):
86
+ """Upload a file to a Slack channel or DM via the external-upload API."""
87
+
88
+ action: Literal["upload_file"] = "upload_file"
89
+ channel: str = Field(
90
+ ...,
91
+ description=(
92
+ "Target Channel ID (C/G/D/Z...) or User ID (U/W...) to share the file with. "
93
+ "Channel names like #general are not accepted by Slack's external upload API."
94
+ ),
95
+ )
96
+ filename: str = Field(default="", description="Display name for the uploaded file.")
97
+ initial_comment: str = Field(default="", description="Message posted alongside the file.")
98
+ filepath: str = Field(
99
+ default="",
100
+ description=(
101
+ "Absolute path to a file under the sandboxed attachments directory "
102
+ "(NW_SLACK_ATTACHMENTS_DIR). Mutually exclusive with content_base64."
103
+ ),
104
+ )
105
+ content_base64: str = Field(
106
+ default="",
107
+ description="Base64-encoded file content. Mutually exclusive with filepath.",
108
+ )
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Output
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ class SlackOutput(BaseModel):
117
+ """Unified output envelope for all Slack actions."""
118
+
119
+ ok: bool = Field(..., description="True when Slack acknowledged the request.")
120
+ ts: Optional[str] = Field(default=None, description="Message timestamp (chat actions).")
121
+ file_id: Optional[str] = Field(default=None, description="File ID (upload action).")
122
+ channel: Optional[str] = Field(default=None, description="Channel the message was sent to.")
123
+ description: str = Field(default="", description="Human-readable summary of the outcome.")
124
+ raw: Dict[str, Any] = Field(default_factory=dict, description="Full Slack API response.")
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: node-wire-slack
3
+ Version: 1.1.0
4
+ Summary: Node Wire connector for Slack: post channel messages, send direct messages and upload files
5
+ Author-email: AOT Technologies <opensource@aot-technologies.com>
6
+ Maintainer-email: AOT Technologies <opensource@aot-technologies.com>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/AOT-Technologies/node-wire
9
+ Project-URL: Documentation, https://aot-technologies.github.io/node-wire/slack_connector/
10
+ Project-URL: Repository, https://github.com/AOT-Technologies/node-wire
11
+ Project-URL: Issues, https://github.com/AOT-Technologies/node-wire/issues
12
+ Project-URL: Changelog, https://github.com/AOT-Technologies/node-wire/blob/main/CHANGELOG.md
13
+ Keywords: node-wire,connector,mcp,slack,chat,messaging
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Operating System :: Microsoft :: Windows
19
+ Classifier: Operating System :: POSIX :: Linux
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: Implementation :: CPython
26
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
27
+ Classifier: Topic :: Communications :: Chat
28
+ Requires-Python: >=3.11
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: node-wire-runtime>=1.1.0
32
+ Requires-Dist: httpx[http2]<0.28.0,>=0.27.0
33
+ Dynamic: license-file
34
+
35
+ <!--
36
+ SPDX-FileCopyrightText: 2026 AOT Technologies
37
+
38
+ SPDX-License-Identifier: Apache-2.0
39
+ -->
40
+
41
+ # node-wire-slack
42
+
43
+ Slack connector for Node Wire. Lets an agent or app post messages to channels, send direct
44
+ messages to users, and upload files, using a Slack bot token.
45
+
46
+ Part of [Node Wire](https://github.com/AOT-Technologies/node-wire). Every call runs through the
47
+ Node Wire runtime, so it gets input validation, retries with a circuit breaker, scope policy,
48
+ a shared error taxonomy, and OpenTelemetry tracing. A Node Wire host exposes each action over REST,
49
+ gRPC and MCP.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install node-wire-slack
55
+ ```
56
+
57
+ This pulls in [`node-wire-runtime`](https://pypi.org/project/node-wire-runtime/). Pre-releases
58
+ are published as `X.Y.ZbN`; install one with `pip install --pre node-wire-slack`. To install
59
+ every connector at once, use [`node-wire-connectors`](https://pypi.org/project/node-wire-connectors/).
60
+
61
+ The wheel is pure Python (`py3-none-any`) and installs on CPython 3.11, 3.12 and 3.13 on any
62
+ OS and CPU.
63
+
64
+ ## Actions
65
+
66
+ The connector registers as `slack`. MCP tool names are `<connector_id>_<action>`, with
67
+ dots replaced by underscores.
68
+
69
+ | Action | MCP tool | What it does |
70
+ |---|---|---|
71
+ | `post_message` | `slack_post_message` | Posts a message, with optional Block Kit blocks, to a channel ID, `#channel-name` or user |
72
+ | `send_direct_message` | `slack_send_direct_message` | Sends a private message to a user, opening the DM if needed |
73
+ | `upload_file` | `slack_upload_file` | Uploads a file (base64 content, or a file from the attachments directory) and shares it to a channel or DM |
74
+
75
+ ## Configuration
76
+
77
+ Add the connector to `config/connectors.yaml`:
78
+
79
+ ```yaml
80
+ connectors:
81
+ slack:
82
+ enabled: true
83
+ exposed_via: ["rest", "grpc", "mcp"]
84
+ auth:
85
+ provider: static_token
86
+ secret_key: SLACK_BOT_TOKEN
87
+ ```
88
+
89
+ Secrets are read through the configured secret provider (environment variables by default):
90
+
91
+ | Variable | Purpose |
92
+ |---|---|
93
+ | `SLACK_BOT_TOKEN` | Bot user OAuth token (`xoxb-...`). Needs the `chat:write`, `files:write` and `im:write` scopes |
94
+ | `NW_SLACK_ATTACHMENTS_DIR` | Optional. The only directory `upload_file` may read from disk (default `/slack_attachments`) |
95
+ | `NW_SLACK_UPLOAD_LIMIT_MB` | Optional. Largest file `upload_file` accepts, in MB (default `50`, capped at `100`) |
96
+
97
+ ## Usage
98
+
99
+ Set `NW_ALLOWED_CONNECTORS=slack` (comma-separate several). Node Wire loads only the
100
+ connectors listed there, and discovers them through the `node_wire.connectors` entry point.
101
+ A Node Wire host (the REST, gRPC or MCP server, or `ConnectorFactory`) then builds the connector
102
+ from the configuration above. See [Use a connector](https://aot-technologies.github.io/node-wire/connectors/).
103
+
104
+ ## Security notes
105
+
106
+ `upload_file` reads local files only from inside `NW_SLACK_ATTACHMENTS_DIR`. The path must be
107
+ absolute, and is refused if it resolves outside that directory, including through a symlink.
108
+
109
+ ## Documentation
110
+
111
+ - [Node Wire on GitHub](https://github.com/AOT-Technologies/node-wire): source, issues and full documentation
112
+ - [Slack setup guide](https://aot-technologies.github.io/node-wire/slack_connector/): bot setup, channel resolution and error codes
113
+ - [Connector reference](https://aot-technologies.github.io/node-wire/connector-reference/#slack)
114
+ - [Configuration](https://aot-technologies.github.io/node-wire/configuration/)
115
+ - [Error codes](https://aot-technologies.github.io/node-wire/errors/)
116
+ - [Changelog](https://github.com/AOT-Technologies/node-wire/blob/main/CHANGELOG.md)
117
+
118
+ ## License
119
+
120
+ Apache-2.0. See [LICENSE](https://github.com/AOT-Technologies/node-wire/blob/main/LICENSE).
@@ -0,0 +1,10 @@
1
+ node_wire_slack/__init__.py,sha256=7NbxPV5wfxs4WOVIyFmAIIKNHakN9WZaTszp-QjGMjw,121
2
+ node_wire_slack/exceptions.py,sha256=Pp4zPFiEuha50SDwqjk-6aFmx9rUL6mZinXGEjMggg0,948
3
+ node_wire_slack/logic.py,sha256=XUyvZm4Z6XMVj_8MuUjV2HvSS-k-wvKmxvyTOfMGv_I,18893
4
+ node_wire_slack/schema.py,sha256=yVB-J7mgQLDHlSy6g0W1ieg8v_dheaerhR9QFU1F0zA,4652
5
+ node_wire_slack-1.1.0.dist-info/licenses/LICENSE,sha256=Fv-HXR30Pfr4aC0Tr3x9cijFVeo5CIgJElNfzPZ0ZdY,11346
6
+ node_wire_slack-1.1.0.dist-info/METADATA,sha256=h0eXMNu4hZ0tzxpa5O1SSzRZso_F-b7wVRSSnsBNnWU,5319
7
+ node_wire_slack-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ node_wire_slack-1.1.0.dist-info/entry_points.txt,sha256=mZTB5kLOpmpdA2bJ5jzzNxXgGwvKv7dv3fdNOzqRLUI,53
9
+ node_wire_slack-1.1.0.dist-info/top_level.txt,sha256=z0xpszVRwfdBy3x2IQ3k26rQJWPbWVWkjbG54NWiHBk,16
10
+ node_wire_slack-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [node_wire.connectors]
2
+ slack = node_wire_slack.logic
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 AOT Technologies
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ node_wire_slack