viasocket 0.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.
viasocket/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """
2
+ viasocket — the 2,300+ apps each of your users connected through viaSocket, as tools for your agent.
3
+
4
+ from viasocket import ViaSocket
5
+ from viasocket.langchain import viasocket_tools # or viasocket.crewai / viasocket.llamaindex
6
+
7
+ viasocket = ViaSocket(org_id, project_id, secret=os.environ["VIASOCKET_EMBED_SECRET"])
8
+ tools = viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]})
9
+ """
10
+
11
+ from ._agent_tools import AgentTool, action_input_schema, agent_tools
12
+ from ._client import ViaSocket, ViaSocketError, sign_embed_token
13
+
14
+ __all__ = ["ViaSocket", "ViaSocketError", "sign_embed_token", "AgentTool", "agent_tools", "action_input_schema"]
15
+ __version__ = "0.1.0"
@@ -0,0 +1,263 @@
1
+ """
2
+ The actions of apps a user connected, as tools an AI agent can call — framework-neutral: a name, a
3
+ description, a JSON Schema for the input and an `invoke`. The same tools, built the same way, as
4
+ `agentTools` in the `viasocket-apps` npm package; `viasocket.langchain`, `viasocket.crewai` and
5
+ `viasocket.llamaindex` wrap them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass
13
+ from typing import Any, Callable, Dict, List, Optional
14
+
15
+ from ._client import ViaSocket, ViaSocketError
16
+
17
+ MAX_RESULT = 20_000
18
+
19
+ JsonSchema = Dict[str, Any]
20
+
21
+
22
+ @dataclass
23
+ class AgentTool:
24
+ """`name` is unique and inside the 64 characters model APIs allow (`slack_send-message`)."""
25
+
26
+ name: str
27
+ description: str
28
+ parameters: JsonSchema
29
+ # Runs the action and answers what the model reads: the result as JSON, or the error as a sentence
30
+ # it can act on. Never raises for those, so one bad call does not end the agent's run.
31
+ invoke: Callable[[Dict[str, Any]], str]
32
+
33
+
34
+ def _event_path(name: str) -> str:
35
+ """`Send Message` -> `send-message`, as the app's page names an event."""
36
+ return re.sub(r"^-+|-+$", "", re.sub(r"[^a-z0-9]+", "-", (name or "").lower()))
37
+
38
+
39
+ def _tool_name(slug: str, action: str) -> str:
40
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", f"{slug}_{_event_path(action)}")[:64]
41
+
42
+
43
+ def _static_values(block: dict) -> Optional[list]:
44
+ """The fixed values of a dropdown, or None for a picker whose values come from the user's account."""
45
+ if block.get("enableSearchApi") or block.get("willDynamicFetchOptions"):
46
+ return None
47
+ values = [option.get("value") for option in block.get("options") or [] if isinstance(option, dict)]
48
+ values = [value for value in values if value is not None and value != ""]
49
+ return values or None
50
+
51
+
52
+ def _describe(block: dict, picker: Optional[str]) -> str:
53
+ parts = [block.get("label"), block.get("help") or block.get("customHelp")]
54
+ if picker:
55
+ parts.append(picker)
56
+ if block.get("dateFormat"):
57
+ parts.append(f"Format: {block['dateFormat']}.")
58
+ # A choice field's placeholder is UI copy ("Select Channel"); only a typed value's is an example.
59
+ if block.get("placeholder") and block.get("type") not in ("dropdown", "multiselect", "boolean"):
60
+ parts.append(f"Example: {block['placeholder']}")
61
+ # The condition is JavaScript over the other fields, which a model reads well once the prefix is gone.
62
+ if block.get("visibilityCondition"):
63
+ parts.append("Only when: " + re.sub(r"context\??\.inputData\??\.?", "", block["visibilityCondition"]))
64
+ return " — ".join(part for part in parts if part)
65
+
66
+
67
+ PickerHint = Callable[[str], str]
68
+
69
+
70
+ def _field_schema(block: dict, key: str, steps: dict, blocks: dict, hint: PickerHint) -> Optional[JsonSchema]:
71
+ kind = block.get("type")
72
+ picker = lambda: hint(block.get("key") or key) # noqa: E731
73
+ if kind in ("string", "markdown", "aifield", "date"):
74
+ return {"type": "string", "description": _describe(block, None)}
75
+ if kind == "number":
76
+ return {"type": "number", "description": _describe(block, None)}
77
+ if kind == "boolean":
78
+ return {"type": "boolean", "description": _describe(block, None)}
79
+ if kind == "dropdown":
80
+ values = _static_values(block)
81
+ if values:
82
+ return {"enum": values, "description": _describe(block, None)}
83
+ return {"type": "string", "description": _describe(block, picker())}
84
+ if kind == "multiselect":
85
+ values = _static_values(block)
86
+ return {
87
+ "type": "array",
88
+ "items": {"enum": values} if values else {"type": "string"},
89
+ "description": _describe(block, None if values else picker()),
90
+ }
91
+ if kind == "dictionary":
92
+ return {"type": "object", "additionalProperties": {"type": "string"}, "description": _describe(block, None)}
93
+ if kind == "input groups":
94
+ return {**_object_schema(key, steps, blocks, hint), "description": _describe(block, None)}
95
+ return None
96
+
97
+
98
+ def _object_schema(parent: str, steps: dict, blocks: dict, hint: PickerHint) -> JsonSchema:
99
+ properties: Dict[str, JsonSchema] = {}
100
+ required: List[str] = []
101
+ for key in steps.get(parent) or []:
102
+ block = blocks.get(key)
103
+ if not isinstance(block, dict):
104
+ continue
105
+ schema = _field_schema(block, key, steps, blocks, hint)
106
+ if schema is None:
107
+ continue
108
+ # `destination.channel_id` is `channel_id` inside `destination`, as inputData nests it.
109
+ name = key[key.rfind(".") + 1 :]
110
+ properties[name] = schema
111
+ # A field shown only under a condition cannot be required of every call.
112
+ if block.get("required") and not block.get("visibilityCondition"):
113
+ required.append(name)
114
+ return {"type": "object", "properties": properties, **({"required": required} if required else {})}
115
+
116
+
117
+ def action_input_schema(input_schema: dict, hint: Optional[PickerHint] = None) -> JsonSchema:
118
+ """An action's `input_schema` — the form viaSocket renders — as the JSON Schema a model fills."""
119
+ hint = hint or (lambda field: "An id from the user's account, not a display name.")
120
+ return _object_schema("root", (input_schema or {}).get("steps") or {}, (input_schema or {}).get("blocks") or {}, hint)
121
+
122
+
123
+ def _clip(text: str) -> str:
124
+ return f"{text[:MAX_RESULT]}… (truncated)" if len(text) > MAX_RESULT else text
125
+
126
+
127
+ def agent_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optional[Dict[str, List[str]]] = None) -> List[AgentTool]:
128
+ """
129
+ One tool per chosen action of each app, for one end user (`user`, the unique identifier their
130
+ connections were made under). An app left out of `actions` gets every published action. Reads the
131
+ public catalog only; the user's connection is looked up when a tool first runs.
132
+ """
133
+ taken: set = set()
134
+
135
+ def unique_name(slug: str, action: str) -> str:
136
+ base = _tool_name(slug, action)
137
+ name, n = base, 2
138
+ while name in taken:
139
+ name, n = f"{base[:60]}_{n}", n + 1
140
+ taken.add(name)
141
+ return name
142
+
143
+ tools: List[AgentTool] = []
144
+ for slug in apps or []:
145
+ service_id = viasocket.service_id_for(slug)
146
+ app = viasocket.versions(service_id)
147
+ if not app:
148
+ raise ViaSocketError(f'agent_tools: "{slug}" has nothing published')
149
+ app_name = app["service"]["name"]
150
+ wanted = (actions or {}).get(slug)
151
+ if wanted:
152
+ chosen = []
153
+ for event in wanted:
154
+ match = next((a for a in app["actions"] if a.get("action_id") == event or _event_path(a.get("name", "")) == event), None)
155
+ if not match:
156
+ raise ViaSocketError(f'agent_tools: {app_name} has no published action "{event}"')
157
+ chosen.append(match)
158
+ else:
159
+ chosen = app["actions"]
160
+ tools.extend(_app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name, taken))
161
+ return tools
162
+
163
+
164
+ def _app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name, taken) -> List[AgentTool]:
165
+ not_connected = f"{app_name} is not connected for this user. Ask them to connect it, then try again."
166
+ # The user's enabled flow for this app: its id runs actions, its auth_id reads their account.
167
+ # Only a found one is kept, so an app the user connects mid-conversation works on the next call.
168
+ found: Dict[str, Any] = {}
169
+
170
+ def find_flow() -> Optional[dict]:
171
+ if "flow" not in found:
172
+ flow = next(
173
+ (f for f in viasocket.list_flows(user) if f["service_id"] == service_id and f["status"] in ("active", "paused")),
174
+ None,
175
+ )
176
+ if flow is None:
177
+ return None
178
+ found["flow"] = flow
179
+ return found["flow"]
180
+
181
+ options_tool = unique_name(slug, "list options")
182
+ with_pickers: Dict[str, dict] = {}
183
+ tools: List[AgentTool] = []
184
+
185
+ for action in chosen:
186
+ name = unique_name(slug, action.get("name", ""))
187
+
188
+ def hint(field: str, name: str = name, action: dict = action) -> str:
189
+ with_pickers[name] = action
190
+ return (
191
+ f"An id from the user's {app_name} account, never a display name or a guess: "
192
+ f'get it with {options_tool} (tool "{name}", field "{field}").'
193
+ )
194
+
195
+ def invoke(input: Dict[str, Any], action: dict = action) -> str:
196
+ try:
197
+ flow = find_flow()
198
+ if not flow:
199
+ return not_connected
200
+ result = viasocket.run_action(flow["id"], action["action_version_id"], input or {})
201
+ return _clip(result if isinstance(result, str) else json.dumps(result))
202
+ except ViaSocketError as error:
203
+ return f"{app_name} {action.get('name')} failed: {error}"
204
+
205
+ tools.append(
206
+ AgentTool(
207
+ name=name,
208
+ description=f"{app_name}: {action.get('description') or action.get('name')}",
209
+ parameters=action_input_schema(action.get("input_schema") or {}, hint),
210
+ invoke=invoke,
211
+ )
212
+ )
213
+
214
+ if not with_pickers:
215
+ taken.discard(options_tool)
216
+ return tools
217
+
218
+ def list_options(input: Dict[str, Any]) -> str:
219
+ action = with_pickers.get(str((input or {}).get("tool", "")))
220
+ if not action:
221
+ return f'Unknown tool "{(input or {}).get("tool")}": use one of {", ".join(with_pickers)}.'
222
+ try:
223
+ flow = find_flow()
224
+ if not flow:
225
+ return not_connected
226
+ chosen_so_far = input.get("chosen") if isinstance(input.get("chosen"), dict) else {}
227
+ existing = {**chosen_so_far, "_searchText": str(input["search"])} if input.get("search") else chosen_so_far
228
+ result = viasocket.list_options(user, action["action_version_id"], str(input.get("field", "")), flow["auth_id"], existing)
229
+ if not result["options"]:
230
+ return 'No values. If this field depends on another, put that one in "chosen" first, or try other search words.'
231
+ values = [{"label": o.get("label"), "value": o.get("value")} for o in result["options"]]
232
+ return _clip(json.dumps({"options": values, "more": bool(result["offset"])}))
233
+ except ViaSocketError as error:
234
+ return f"{app_name}: listing values failed: {error}"
235
+
236
+ tools.append(
237
+ AgentTool(
238
+ name=options_tool,
239
+ description=(
240
+ f"{app_name}: lists the values a field of another {app_name} tool accepts (a channel, a sheet, a list), "
241
+ f"read from the user's own {app_name} account. Call it before filling a field whose description names "
242
+ "this tool; send the value, show the label."
243
+ ),
244
+ parameters={
245
+ "type": "object",
246
+ "properties": {
247
+ "tool": {"enum": list(with_pickers), "description": "The tool whose field needs values."},
248
+ "field": {"type": "string", "description": 'The field, exactly as its description names it, such as "destination.channel_id".'},
249
+ "chosen": {
250
+ "type": "object",
251
+ "description": (
252
+ "What is already chosen for that tool, in the same shape as its input. A field that depends on "
253
+ "another (a sheet inside a spreadsheet) lists nothing until that one is here."
254
+ ),
255
+ },
256
+ "search": {"type": "string", "description": "Words to narrow a long list, such as part of a channel name."},
257
+ },
258
+ "required": ["tool", "field"],
259
+ },
260
+ invoke=list_options,
261
+ )
262
+ )
263
+ return tools
viasocket/_client.py ADDED
@@ -0,0 +1,214 @@
1
+ """
2
+ The part of the viaSocket Apps API an agent needs, with no dependencies: the public catalog, the
3
+ signed embed token, a user's flows and field values, and running an action. Mirrors the calls of
4
+ the `viasocket-apps` npm package, so both read the same responses the same way.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from typing import Any, Callable, Dict, List, Optional
18
+
19
+ DEFAULT_API_BASE_URL = "https://flow-api.viasocket.com"
20
+ DEFAULT_RUN_BASE_URL = "https://flow.sokt.io"
21
+ CATALOG_VERSIONS = "https://flow.sokt.io/func/scriK4LFg2kc"
22
+ CATALOG_SLUG = "https://plug-service.viasocket.com/api/v1/plugins/recommend/services"
23
+ # An unknown slug is answered by nothing, slowly; a known one in well under a second.
24
+ SLUG_TIMEOUT = 30
25
+ REQUEST_TIMEOUT = 120
26
+ VERSIONS_TTL = 10 * 60
27
+
28
+ # (method, url, headers, body) -> (status, text). Swapped in tests; urllib otherwise.
29
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], "tuple[int, str]"]
30
+
31
+
32
+ class ViaSocketError(Exception):
33
+ """A refusal from viaSocket, with the API's own message; `status` is None for a local check."""
34
+
35
+ def __init__(self, message: str, status: Optional[int] = None, body: Any = None):
36
+ super().__init__(message)
37
+ self.status = status
38
+ self.body = body
39
+
40
+
41
+ def _urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float):
42
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
43
+ try:
44
+ with urllib.request.urlopen(req, timeout=timeout) as response:
45
+ return response.status, response.read().decode("utf-8")
46
+ except urllib.error.HTTPError as error:
47
+ return error.code, error.read().decode("utf-8", "replace")
48
+ except (urllib.error.URLError, TimeoutError) as error:
49
+ raise ViaSocketError(f"Request to {url} failed: {getattr(error, 'reason', error)}") from error
50
+
51
+
52
+ def _b64url(data: bytes) -> str:
53
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
54
+
55
+
56
+ def sign_embed_token(org_id: str, project_id: str, unique_identifier: str, secret: str) -> str:
57
+ """The embed token: an HS256 JWT of exactly { org_id, project_id, unique_identifier }."""
58
+ for name, value in (("org_id", org_id), ("project_id", project_id), ("unique_identifier", unique_identifier), ("secret", secret)):
59
+ if not isinstance(value, str) or not value:
60
+ raise ViaSocketError(f"sign_embed_token: {name} is required")
61
+ compact = {"separators": (",", ":"), "ensure_ascii": False}
62
+ header = _b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, **compact).encode())
63
+ payload = _b64url(
64
+ json.dumps({"org_id": org_id, "project_id": project_id, "unique_identifier": unique_identifier}, **compact).encode()
65
+ )
66
+ signing_input = f"{header}.{payload}"
67
+ signature = hmac.new(secret.encode(), signing_input.encode(), hashlib.sha256).digest()
68
+ return f"{signing_input}.{_b64url(signature)}"
69
+
70
+
71
+ def _required(name: str, value: Any) -> str:
72
+ if not isinstance(value, str) or not value.strip():
73
+ raise ViaSocketError(f"{name} is required")
74
+ return value
75
+
76
+
77
+ class ViaSocket:
78
+ """The server-side client. `secret` is the embed secret: keep it on the server."""
79
+
80
+ def __init__(
81
+ self,
82
+ org_id: str,
83
+ project_id: str,
84
+ secret: str,
85
+ api_base_url: str = DEFAULT_API_BASE_URL,
86
+ run_base_url: str = DEFAULT_RUN_BASE_URL,
87
+ transport: Optional[Transport] = None,
88
+ ):
89
+ self.org_id = _required("org_id", org_id)
90
+ self.project_id = _required("project_id", project_id)
91
+ self._secret = _required("secret", secret)
92
+ self.api_base_url = api_base_url.rstrip("/")
93
+ self.run_base_url = run_base_url.rstrip("/")
94
+ self._transport = transport or _urllib_transport
95
+ self._service_ids: Dict[str, str] = {}
96
+ self._versions: Dict[str, "tuple[float, Optional[dict]]"] = {}
97
+
98
+ def _request(self, method: str, url: str, body: Any = None, token: Optional[str] = None, timeout: float = REQUEST_TIMEOUT) -> Any:
99
+ """
100
+ The envelope `{ success, data }` is unwrapped and a refusal raised. A body is the envelope only
101
+ when it has a boolean `success` and a `data` key (or is `success: false`): many actions answer
102
+ with their own result at the top level, which is returned whole.
103
+ """
104
+ # urllib's default User-Agent is refused (403) by the catalog's firewall.
105
+ headers = {"Content-Type": "application/json", "User-Agent": "viasocket-python"}
106
+ if token:
107
+ headers["authorization"] = token
108
+ data = None if body is None else (body if isinstance(body, bytes) else json.dumps(body).encode())
109
+ status, text = self._transport(method, url, headers, data, timeout)
110
+ try:
111
+ payload = json.loads(text) if text else None
112
+ except ValueError:
113
+ payload = text
114
+ envelope = (
115
+ payload
116
+ if isinstance(payload, dict) and isinstance(payload.get("success"), bool) and ("data" in payload or payload["success"] is False)
117
+ else None
118
+ )
119
+ if not 200 <= status < 300 or (envelope is not None and envelope["success"] is False):
120
+ raw = payload if isinstance(payload, dict) else {}
121
+ error = raw.get("error")
122
+ message = (
123
+ raw.get("message")
124
+ or (error.get("message") if isinstance(error, dict) else None)
125
+ or f"viaSocket responded {status} for {method} {url}"
126
+ )
127
+ raise ViaSocketError(message, status=status, body=payload)
128
+ return envelope["data"] if envelope is not None else payload
129
+
130
+ # The catalog: public, nothing per user.
131
+
132
+ def service_id_for(self, slug: str) -> str:
133
+ """The `service_id` of the app with this slug (`slack`, `google-sheets`). Exact and case-sensitive."""
134
+ key = _required("slug", slug)
135
+ if key not in self._service_ids:
136
+ url = f"{CATALOG_SLUG}?service={urllib.parse.quote(key)}"
137
+ try:
138
+ data = self._request("GET", url, timeout=SLUG_TIMEOUT)
139
+ except ViaSocketError as error:
140
+ if "timed out" not in str(error):
141
+ raise
142
+ data = None
143
+ inner = data.get("data") if isinstance(data, dict) else None
144
+ plugins = (inner.get("plugins") if isinstance(inner, dict) else None) or {}
145
+ service_id = (plugins.get(key) or {}).get("rowid")
146
+ if not service_id:
147
+ raise ViaSocketError(f'No viaSocket app has the slug "{key}" (slugs are exact and case-sensitive)')
148
+ self._service_ids[key] = service_id
149
+ return self._service_ids[key]
150
+
151
+ def versions(self, service_id: str) -> Optional[dict]:
152
+ """One app with its published actions and triggers, or None for an unknown service id. Cached 10 minutes."""
153
+ cached = self._versions.get(service_id)
154
+ if cached and time.time() - cached[0] < VERSIONS_TTL:
155
+ return cached[1]
156
+ data = self._request("POST", CATALOG_VERSIONS, {"service_id": _required("service_id", service_id)})
157
+ # No `success` key, so the body arrives whole; tolerate an envelope anyway.
158
+ body = data if isinstance(data, dict) else {}
159
+ if "service" not in body:
160
+ body = body.get("data") if isinstance(body.get("data"), dict) else {}
161
+ service = body.get("service") or {}
162
+ if not service.get("name"):
163
+ return None
164
+ app = {
165
+ "service": service,
166
+ "actions": body.get("actions") if isinstance(body.get("actions"), list) else [],
167
+ "triggers": body.get("triggers") if isinstance(body.get("triggers"), list) else [],
168
+ }
169
+ self._versions[service_id] = (time.time(), app)
170
+ return app
171
+
172
+ # Calls for one end user.
173
+
174
+ def token_for(self, unique_identifier: str) -> str:
175
+ return sign_embed_token(self.org_id, self.project_id, _required("unique_identifier", unique_identifier), self._secret)
176
+
177
+ def list_flows(self, unique_identifier: str) -> List[dict]:
178
+ """Every flow the user has: one per enabled app, one per trigger subscription."""
179
+ data = self._request("GET", f"{self.api_base_url}/projects/{self.project_id}/integrations", token=self.token_for(unique_identifier))
180
+ return [
181
+ {
182
+ "id": flow.get("id"),
183
+ "status": flow.get("status"),
184
+ "auth_id": flow.get("auth_id"),
185
+ "service_id": flow.get("service_id"),
186
+ "title": flow.get("title"),
187
+ }
188
+ for flow in ((data or {}).get("flows") or [])
189
+ ]
190
+
191
+ def list_options(self, unique_identifier: str, action_version_id: str, field_key: str, auth_id: str, existing_fields: Optional[dict] = None) -> dict:
192
+ """The values one field accepts, read from the user's own account: `{ options, offset }`."""
193
+ data = self._request(
194
+ "POST",
195
+ f"{self.api_base_url}/embed/list-options/{_required('action_version_id', action_version_id)}",
196
+ {"fieldKey": _required("field_key", field_key), "auth_id": _required("auth_id", auth_id), "existingFields": existing_fields or {}},
197
+ token=self.token_for(unique_identifier),
198
+ )
199
+ if isinstance(data, list):
200
+ return {"options": data, "offset": None}
201
+ # A connection that cannot be read answers 200 with the failure nested inside.
202
+ response = (data or {}).get("response") if isinstance(data, dict) else None
203
+ if isinstance(response, dict) and int(response.get("status") or 0) >= 400:
204
+ raise ViaSocketError(((response.get("data") or {}).get("message")) or "list-options failed", status=int(response["status"]), body=data)
205
+ options = (data or {}).get("data") if isinstance(data, dict) else None
206
+ return {"options": options if isinstance(options, list) else [], "offset": (data or {}).get("offset")}
207
+
208
+ def run_action(self, script_id: str, action_version_id: str, input_data: Optional[dict] = None) -> Any:
209
+ """Runs one action. The script_id from the user's enabled flow is the credential: server only."""
210
+ return self._request(
211
+ "POST",
212
+ f"{self.run_base_url}/func/{_required('script_id', script_id)}",
213
+ {"action_version_id": _required("action_version_id", action_version_id), "inputData": input_data or {}},
214
+ )
viasocket/_pydantic.py ADDED
@@ -0,0 +1,75 @@
1
+ """
2
+ CrewAI and LlamaIndex take a tool's input as a Pydantic model, not a JSON Schema: this builds one
3
+ from the schema `agent_tools` makes, keeping every description, enum and required field, and turns a
4
+ model's validated input back into the plain dict viaSocket takes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import keyword
10
+ import re
11
+ from typing import Any, Dict, List, Literal, Optional, Type
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field, create_model
14
+
15
+
16
+ class _Input(BaseModel):
17
+ model_config = ConfigDict(populate_by_name=True, extra="allow")
18
+
19
+
20
+ def _identifier(key: str, taken: set) -> str:
21
+ """A Python name for a field key (`blockit-kit-ai`, `_searchText`); the key stays its alias."""
22
+ name = re.sub(r"\W", "_", key).lstrip("_") or "field"
23
+ if name[0].isdigit() or keyword.iskeyword(name) or hasattr(BaseModel, name):
24
+ name = f"f_{name}"
25
+ while name in taken:
26
+ name += "_"
27
+ taken.add(name)
28
+ return name
29
+
30
+
31
+ def _type_of(schema: Dict[str, Any], name: str) -> Any:
32
+ if "enum" in schema:
33
+ values = schema["enum"]
34
+ return Literal[tuple(values)] if values and all(isinstance(v, (str, int, bool)) for v in values) else Any
35
+ kind = schema.get("type")
36
+ if kind == "string":
37
+ return str
38
+ if kind == "number":
39
+ return float
40
+ if kind == "boolean":
41
+ return bool
42
+ if kind == "array":
43
+ return List[_type_of(schema.get("items") or {}, f"{name}Item")]
44
+ if kind == "object" and schema.get("properties"):
45
+ return model_from_schema(name, schema)
46
+ if kind == "object":
47
+ return Dict[str, Any]
48
+ return Any
49
+
50
+
51
+ def model_from_schema(name: str, schema: Dict[str, Any]) -> Type[BaseModel]:
52
+ """A Pydantic model for an object schema; nested objects become nested models."""
53
+ required = set(schema.get("required") or [])
54
+ taken: set = set()
55
+ fields: Dict[str, Any] = {}
56
+ for key, prop in (schema.get("properties") or {}).items():
57
+ field_type = _type_of(prop, f"{name}_{_identifier(key, set())}")
58
+ description = prop.get("description")
59
+ if key in required:
60
+ fields[_identifier(key, taken)] = (field_type, Field(..., alias=key, description=description))
61
+ else:
62
+ fields[_identifier(key, taken)] = (Optional[field_type], Field(None, alias=key, description=description))
63
+ model_name = re.sub(r"\W", "_", name) or "Input"
64
+ return create_model(model_name, __base__=_Input, **fields)
65
+
66
+
67
+ def to_plain(value: Any) -> Any:
68
+ """A model's input as viaSocket takes it: original keys, fields left out not sent."""
69
+ if isinstance(value, BaseModel):
70
+ return to_plain(value.model_dump(by_alias=True, exclude_none=True))
71
+ if isinstance(value, dict):
72
+ return {k: to_plain(v) for k, v in value.items() if v is not None}
73
+ if isinstance(value, list):
74
+ return [to_plain(v) for v in value]
75
+ return value
viasocket/crewai.py ADDED
@@ -0,0 +1,42 @@
1
+ """
2
+ viasocket.crewai — the apps a user connected, as CrewAI tools.
3
+
4
+ from viasocket import ViaSocket
5
+ from viasocket.crewai import viasocket_tools
6
+
7
+ tools = viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]})
8
+ agent = Agent(role="Ops assistant", goal="...", backstory="...", tools=tools)
9
+
10
+ Needs `crewai`: `pip install "viasocket[crewai]"`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Callable, Dict, List, Optional, Type
16
+
17
+ from crewai.tools import BaseTool
18
+ from pydantic import BaseModel
19
+
20
+ from ._agent_tools import agent_tools
21
+ from ._client import ViaSocket
22
+ from ._pydantic import model_from_schema, to_plain
23
+
24
+
25
+ class ViaSocketTool(BaseTool):
26
+ """One viaSocket action; `_run` hands the validated input to viaSocket as it takes it."""
27
+
28
+ name: str
29
+ description: str
30
+ args_schema: Type[BaseModel]
31
+ invoke: Callable[[Dict[str, Any]], str]
32
+
33
+ def _run(self, **kwargs: Any) -> str:
34
+ return self.invoke(to_plain(kwargs))
35
+
36
+
37
+ def viasocket_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optional[Dict[str, List[str]]] = None) -> List[ViaSocketTool]:
38
+ """One CrewAI tool per chosen action; each runs on the user's own connection to the app."""
39
+ return [
40
+ ViaSocketTool(name=t.name, description=t.description, args_schema=model_from_schema(t.name, t.parameters), invoke=t.invoke)
41
+ for t in agent_tools(viasocket, user, apps, actions)
42
+ ]
viasocket/langchain.py ADDED
@@ -0,0 +1,38 @@
1
+ """
2
+ viasocket.langchain — the apps a user connected, as LangChain tools.
3
+
4
+ from viasocket import ViaSocket
5
+ from viasocket.langchain import viasocket_tools
6
+
7
+ tools = viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]})
8
+ agent = create_agent(model, tools)
9
+
10
+ Needs `langchain-core` 0.3 or later: `pip install "viasocket[langchain]"`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Callable, Dict, List, Optional
16
+
17
+ from langchain_core.tools import StructuredTool
18
+
19
+ from ._agent_tools import agent_tools
20
+ from ._client import ViaSocket
21
+
22
+
23
+ def viasocket_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optional[Dict[str, List[str]]] = None) -> List[StructuredTool]:
24
+ """One LangChain tool per chosen action; each runs on the user's own connection to the app."""
25
+ return [
26
+ StructuredTool(
27
+ name=t.name,
28
+ description=t.description,
29
+ args_schema=t.parameters,
30
+ func=_caller(t.invoke),
31
+ )
32
+ for t in agent_tools(viasocket, user, apps, actions)
33
+ ]
34
+
35
+
36
+ def _caller(invoke: Callable[[Dict[str, Any]], str]) -> Callable[..., str]:
37
+ """The tool's function: keyword arguments in, as LangChain calls it, one dict to viaSocket."""
38
+ return lambda **kwargs: invoke(kwargs)
@@ -0,0 +1,39 @@
1
+ """
2
+ viasocket.llamaindex — the apps a user connected, as LlamaIndex tools.
3
+
4
+ from viasocket import ViaSocket
5
+ from viasocket.llamaindex import viasocket_tools
6
+
7
+ tools = viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]})
8
+ agent = FunctionAgent(tools=tools, llm=llm)
9
+
10
+ Needs `llama-index-core` 0.12 or later: `pip install "viasocket[llamaindex]"`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Callable, Dict, List, Optional
16
+
17
+ from llama_index.core.tools import FunctionTool
18
+
19
+ from ._agent_tools import agent_tools
20
+ from ._client import ViaSocket
21
+ from ._pydantic import model_from_schema, to_plain
22
+
23
+
24
+ def viasocket_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optional[Dict[str, List[str]]] = None) -> List[FunctionTool]:
25
+ """One LlamaIndex tool per chosen action; each runs on the user's own connection to the app."""
26
+ return [
27
+ FunctionTool.from_defaults(
28
+ fn=_caller(t.invoke),
29
+ name=t.name,
30
+ description=t.description,
31
+ fn_schema=model_from_schema(t.name, t.parameters),
32
+ )
33
+ for t in agent_tools(viasocket, user, apps, actions)
34
+ ]
35
+
36
+
37
+ def _caller(invoke: Callable[[Dict[str, Any]], str]) -> Callable[..., str]:
38
+ """The tool's function: validated keyword arguments in, one plain dict to viaSocket."""
39
+ return lambda **kwargs: invoke(to_plain(kwargs))
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.5
2
+ Name: viasocket
3
+ Version: 0.1.0
4
+ Summary: viaSocket for Python agents: the 2,300+ apps each of your users connected (Slack, Google Sheets, HubSpot, Notion...) as tools for LangChain, CrewAI and LlamaIndex.
5
+ Project-URL: Homepage, https://github.com/Walkover-Web-Solution/viasocket-apps/tree/main/python#readme
6
+ Project-URL: Source, https://github.com/Walkover-Web-Solution/viasocket-apps
7
+ Author: Walkover Web Solution
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ai-agent,crewai,google-sheets,integrations,langchain,llamaindex,slack,tools,viasocket
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Provides-Extra: crewai
15
+ Requires-Dist: crewai>=0.80; extra == 'crewai'
16
+ Provides-Extra: langchain
17
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
18
+ Provides-Extra: llamaindex
19
+ Requires-Dist: llama-index-core>=0.12; extra == 'llamaindex'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # viasocket (Python)
23
+
24
+ Your own agent, acting in the apps each of your users connected through viaSocket: every action of
25
+ an app is a tool, run on that user's own connection. Slack's Send Message, Google Sheets' Add New
26
+ Row, HubSpot's Create Deal — any of 2,300+ apps, with no connector code and no OAuth on your side.
27
+ Works with LangChain, CrewAI and LlamaIndex.
28
+
29
+ It is the Python side of the [`viasocket-apps`](https://www.npmjs.com/package/viasocket-apps) npm
30
+ package, and builds the same tools from the same catalog. No dependencies of its own; Python 3.10+.
31
+
32
+ ```sh
33
+ pip install "viasocket[langchain]" # or [crewai], [llamaindex]
34
+ ```
35
+
36
+ You need three values: `VIASOCKET_ORG_ID`, `VIASOCKET_PROJECT_ID` and `VIASOCKET_EMBED_SECRET`. With Node.js,
37
+ `npx viasocket-apps setup` writes them to `.env` after one click in the browser; without it, copy them from the
38
+ viaSocket dashboard (**Integrations → Create embed → Install Code**). The secret stays on your server.
39
+
40
+ ```python
41
+ import os
42
+ from viasocket import ViaSocket
43
+
44
+ viasocket = ViaSocket(
45
+ org_id=os.environ["VIASOCKET_ORG_ID"],
46
+ project_id=os.environ["VIASOCKET_PROJECT_ID"],
47
+ secret=os.environ["VIASOCKET_EMBED_SECRET"],
48
+ )
49
+ ```
50
+
51
+ ## LangChain
52
+
53
+ ```python
54
+ from langchain.agents import create_agent
55
+ from viasocket.langchain import viasocket_tools
56
+
57
+ tools = viasocket_tools(
58
+ viasocket,
59
+ user="user_123", # the unique identifier the user connected their apps under
60
+ apps=["slack", "google-sheets"],
61
+ actions={"slack": ["send-message"], "google-sheets": ["add-new-row-to-sheet", "lookup-spreadsheet-rows"]},
62
+ )
63
+
64
+ agent = create_agent("anthropic:claude-sonnet-5-5", tools)
65
+ agent.invoke({"messages": [{"role": "user", "content": "Post our Q3 numbers in #finance"}]})
66
+ ```
67
+
68
+ ## CrewAI
69
+
70
+ ```python
71
+ from crewai import Agent
72
+ from viasocket.crewai import viasocket_tools
73
+
74
+ agent = Agent(
75
+ role="Operations assistant",
76
+ goal="Keep the team updated in Slack",
77
+ backstory="You post updates where the team reads them.",
78
+ tools=viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]}),
79
+ )
80
+ ```
81
+
82
+ ## LlamaIndex
83
+
84
+ ```python
85
+ from llama_index.core.agent.workflow import FunctionAgent
86
+ from viasocket.llamaindex import viasocket_tools
87
+
88
+ agent = FunctionAgent(
89
+ tools=viasocket_tools(viasocket, user="user_123", apps=["slack"], actions={"slack": ["send-message"]}),
90
+ llm=llm,
91
+ )
92
+ ```
93
+
94
+ ## How the tools behave
95
+
96
+ - **The user connects the app first**, in your product, through viaSocket's connect popup (see the
97
+ [`viasocket-apps` README](https://github.com/Walkover-Web-Solution/viasocket-apps#browser)). A tool for
98
+ an app they have not connected answers the model "Slack is not connected for this user", so the agent
99
+ can ask them to; it starts working on the next call after they do.
100
+ - **Pick the actions.** An app left out of `actions` gives every published action as a tool — fine for a
101
+ small app, too many for a large one (Notion has 57). Actions are named by `action_id` or by their path
102
+ on the app's page (`send-message`).
103
+ - **Tool names** are `<app>_<action>` (`slack_send-message`); the input schema is built from the action's
104
+ form, so the model sees the same fields, choices and help text a person would.
105
+ - **Fields that hold an id** (a channel, a spreadsheet) come from the user's own account. Each app with
106
+ such a field also gets a `<app>_list-options` tool, which lists the real values on the user's connection.
107
+ - An error from the app comes back to the model as text, not as an exception, so one bad call does not
108
+ end the run.
109
+
110
+ The same tools without a framework — a name, a description, a JSON Schema and `invoke` — are
111
+ `viasocket.agent_tools(viasocket, user, apps, actions)`.
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,11 @@
1
+ viasocket/__init__.py,sha256=zfckk34FDn2aHIbuj9qyxFP7p7Ywjb4E7QWCPdKWYa8,722
2
+ viasocket/_agent_tools.py,sha256=_8qbYSOwb9bYN9sYgoTk8vG7qVpUUnK6DXPk5X27C_o,11896
3
+ viasocket/_client.py,sha256=QM-vNKY697_0Pr3vW6e0apVPIKgiHeKZ9a8jBj5qgzs,10550
4
+ viasocket/_pydantic.py,sha256=9ElDmp11hYbaucpPb4b5zm08f29D6YYlZ7pUbqJrBb4,2884
5
+ viasocket/crewai.py,sha256=9cgfeTpz8PKI7fGhSUT4XTDlvSmp8Q6iwM7eih7tkok,1468
6
+ viasocket/langchain.py,sha256=bKSWB8PVzocE837HwWk46S4tCWeQ7U2Vt7YUw0Yjsag,1320
7
+ viasocket/llamaindex.py,sha256=kjuU-chlkyxNtLdyG9CGGrpV_hUxwy9Lp4sTyYiGEvA,1424
8
+ viasocket-0.1.0.dist-info/METADATA,sha256=X_ifNGP-YR4KEhm1Ys5taGPFWwHXKC_ZYH9BTy7esyE,4708
9
+ viasocket-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ viasocket-0.1.0.dist-info/licenses/LICENSE,sha256=StaJhfljcsZClDExpCBSo5_NAhm_3JJRI1WcpnxrlZI,1078
11
+ viasocket-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Walkover Web Solution
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.