Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(gotify): let agents manage messages, applications and clients (#16522)

Odai Ahmad62fbdc37f49f
diff --git a/bun.lock b/bun.lock
index 2be063fefb0..3adc42ba6a1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4143,15 +4143,15 @@
},
"packages/pieces/community/gotify": {
"name": "@activepieces/piece-gotify",
- "version": "0.4.7",
+ "version": "0.5.0",
"dependencies": {
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/gptzero-detect-ai": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index c961b59d43c..1d9df580612 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Gotify 0.5.0: Send Notification returns the message, and server URLs are checked
+
+Send Notification used to return the whole HTTP response, `{ status, headers, body }`. From Gotify 0.5.0 it returns the created message itself (`id`, `appid`, `message`, `title`, `priority`, `extras`, `date`), which was `body` before. The app token is now sent in the `X-Gotify-Key` header instead of the URL query string, and a priority of `0` is sent as `0` instead of being dropped.
+
+The connection's server URL must now be an `http` or `https` URL without a username, password, query string or fragment (a sub-path such as `https://example.com/gotify` is kept). Connections are checked against the server's `/health` endpoint when saved. TLS certificates are now checked on every request; the old Send Notification skipped this check, so a Gotify server with a self-signed certificate fails after the upgrade.
+
+#### What you need to do
+
+If a later step reads `body.id` or another field under `body` from Send Notification, read it from the top level instead (`id`). A connection whose server URL has credentials or a query string must be updated to the plain server URL. A server with a self-signed certificate needs a certificate from a trusted authority (for example Let's Encrypt), or its CA added to the trust store of the machine running Activepieces (`NODE_EXTRA_CA_CERTS`). Steps keep running on the version they were built with until you upgrade them.
+
#### Discourse 0.3.0: the forum URL must use https and a public address, and actions return flat fields
The Discourse connection used to send your API key to whatever URL was entered, including plain `http://` and local or private network addresses. From 0.3.0 the Website URL must start with `https://` and must not point to `localhost` or a private/LAN IP address; such connections now fail with a clear error, and new connections are checked when you save them.
diff --git a/packages/pieces/community/gotify/package.json b/packages/pieces/community/gotify/package.json
index f243215da24..10db4bd6727 100644
--- a/packages/pieces/community/gotify/package.json
+++ b/packages/pieces/community/gotify/package.json
@@ -1,20 +1,21 @@
{
"name": "@activepieces/piece-gotify",
- "version": "0.4.7",
+ "version": "0.5.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
- "@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/gotify/src/i18n/translation.json b/packages/pieces/community/gotify/src/i18n/translation.json
index 24704bc1597..817ae4bd274 100644
--- a/packages/pieces/community/gotify/src/i18n/translation.json
+++ b/packages/pieces/community/gotify/src/i18n/translation.json
@@ -2,15 +2,78 @@
"Self-hosted push notification service": "Self-hosted push notification service",
"Server URL": "Server URL",
"App Token": "App Token",
- "Gotify Instance URL": "Gotify Instance URL",
- "Gotify App Token": "Gotify App Token",
- "\n To obtain a token:\n\n 1. Log in to your Gotify instance.\n 2. Click on Apps\n 3. Select the Eye icon in the same row as your App to copy your token, or CREATE APPLICATION if you do not have one app yet.\n 4. Copy your access token & and paste them into the fields below.\n ": "\n To obtain a token:\n\n 1. Log in to your Gotify instance.\n 2. Click on Apps\n 3. Select the Eye icon in the same row as your App to copy your token, or CREATE APPLICATION if you do not have one app yet.\n 4. Copy your access token & and paste them into the fields below.\n ",
+ "Client Token": "Client Token",
+ "The address of your Gotify server, e.g. https://gotify.example.com": "The address of your Gotify server, e.g. https://gotify.example.com",
+ "Token of a Gotify application. Used to send notifications.": "Token of a Gotify application. Used to send notifications.",
+ "Token of a Gotify client. Needed to read or delete messages and manage applications.": "Token of a Gotify client. Needed to read or delete messages and manage applications.",
+ "\n To connect Gotify:\n\n 1. Log in to your Gotify web UI.\n 2. Open **Apps**, create an application (or pick one) and copy its token into **App Token**. It is used to send notifications.\n 3. Optional: open **Clients**, create a client and copy its token into **Client Token**. It is needed to read and delete messages and to manage applications.\n ": "\n To connect Gotify:\n\n 1. Log in to your Gotify web UI.\n 2. Open **Apps**, create an application (or pick one) and copy its token into **App Token**. It is used to send notifications.\n 3. Optional: open **Clients**, create a client and copy its token into **Client Token**. It is needed to read and delete messages and to manage applications.\n ",
"Send Notification": "Send Notification",
- "Send a notification to gotify": "Send a notification to gotify",
+ "List Messages": "List Messages",
+ "Delete Message": "Delete Message",
+ "Delete Application Messages": "Delete Application Messages",
+ "List Applications": "List Applications",
+ "Create Application": "Create Application",
+ "Update Application": "Update Application",
+ "Delete Application": "Delete Application",
+ "List Clients": "List Clients",
+ "Get Current User": "Get Current User",
+ "Get Server Health": "Get Server Health",
+ "Custom API Call": "Custom API Call",
+ "Send a push notification through your Gotify server.": "Send a push notification through your Gotify server.",
+ "List messages, newest first, optionally for one application.": "List messages, newest first, optionally for one application.",
+ "Delete one message by its ID.": "Delete one message by its ID.",
+ "Delete all messages of one application.": "Delete all messages of one application.",
+ "List the applications of the connected Gotify user.": "List the applications of the connected Gotify user.",
+ "Create a Gotify application.": "Create a Gotify application.",
+ "Change the name, description or default priority of an application. Gotify replaces all three fields on every update, so fields you leave empty are re-sent with the values read just before the update; do not run two updates of the same application at the same time.": "Change the name, description or default priority of an application. Gotify replaces all three fields on every update, so fields you leave empty are re-sent with the values read just before the update; do not run two updates of the same application at the same time.",
+ "Delete an application and all of its messages.": "Delete an application and all of its messages.",
+ "List the clients (devices) of the connected Gotify user.": "List the clients (devices) of the connected Gotify user.",
+ "Get the Gotify user of the Client Token.": "Get the Gotify user of the Client Token.",
+ "Get the health and version of the Gotify server.": "Get the health and version of the Gotify server.",
"Title": "Title",
"Message": "Message",
"Priority": "Priority",
+ "Render as Markdown": "Render as Markdown",
+ "Click URL": "Click URL",
+ "Big Image URL": "Big Image URL",
+ "Application ID": "Application ID",
+ "Limit": "Limit",
+ "Since": "Since",
+ "Message ID": "Message ID",
+ "Name": "Name",
+ "Description": "Description",
+ "Default Priority": "Default Priority",
+ "Clear Description": "Clear Description",
+ "Method": "Method",
+ "Query Parameters": "Query Parameters",
+ "Body": "Body",
"The title of the notification": "The title of the notification",
"The message to send": "The message to send",
- "The priority of the notification (0-10). 0 is lowest priority.": "The priority of the notification (0-10). 0 is lowest priority."
-}
\ No newline at end of file
+ "0 (lowest) to 10. Empty uses the application default.": "0 (lowest) to 10. Empty uses the application default.",
+ "Ask Gotify clients to render the message as Markdown.": "Ask Gotify clients to render the message as Markdown.",
+ "URL opened when the notification is tapped (http or https).": "URL opened when the notification is tapped (http or https).",
+ "Image shown in the expanded notification on Android (http or https).": "Image shown in the expanded notification on Android (http or https).",
+ "Only list messages of this application. Empty = all.": "Only list messages of this application. Empty = all.",
+ "Maximum number of messages to return (1-200). Default 100.": "Maximum number of messages to return (1-200). Default 100.",
+ "Only messages with a lower ID (nextSince of the previous page).": "Only messages with a lower ID (nextSince of the previous page).",
+ "Numeric ID of the message to delete.": "Numeric ID of the message to delete.",
+ "Numeric ID of the application whose messages are deleted.": "Numeric ID of the application whose messages are deleted.",
+ "Priority (0-10) used for messages sent without one.": "Priority (0-10) used for messages sent without one.",
+ "0-10": "0-10",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
+ "Make a request to any Gotify API endpoint with the Client Token.": "Make a request to any Gotify API endpoint with the Client Token.",
+ "Path": "Path",
+ "Endpoint path on your Gotify server, for example /message or /application/1.": "Endpoint path on your Gotify server, for example /message or /application/1.",
+ "JSON body (ignored for GET).": "JSON body (ignored for GET)."
+}
diff --git a/packages/pieces/community/gotify/src/index.ts b/packages/pieces/community/gotify/src/index.ts
index 4558c0b6baa..07f707a8e28 100644
--- a/packages/pieces/community/gotify/src/index.ts
+++ b/packages/pieces/community/gotify/src/index.ts
@@ -1,21 +1,39 @@
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createApplication } from './lib/actions/create-application';
+import { customApiCall } from './lib/actions/custom-api-call';
+import { deleteApplication } from './lib/actions/delete-application';
+import { deleteApplicationMessages } from './lib/actions/delete-application-messages';
+import { deleteMessage } from './lib/actions/delete-message';
+import { getCurrentUser } from './lib/actions/get-current-user';
+import { getServerHealth } from './lib/actions/get-server-health';
+import { listApplications } from './lib/actions/list-applications';
+import { listClients } from './lib/actions/list-clients';
+import { listMessages } from './lib/actions/list-messages';
import { sendNotification } from './lib/actions/send-notification';
+import { updateApplication } from './lib/actions/update-application';
import { gotifyAuth } from './lib/auth';
export const gotify = createPiece({
displayName: 'Gotify',
description: 'Self-hosted push notification service',
-
logoUrl: 'https://cdn.activepieces.com/pieces/gotify.png',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
categories: [PieceCategory.DEVELOPER_TOOLS],
- authors: ["MyWay","kishanprmr","khaledmashaly","abuaboud"],
+ authors: ['MyWay', 'kishanprmr', 'khaledmashaly', 'abuaboud'],
auth: gotifyAuth,
- actions: [sendNotification],
+ actions: [
+ sendNotification,
+ listMessages,
+ deleteMessage,
+ deleteApplicationMessages,
+ listApplications,
+ createApplication,
+ updateApplication,
+ deleteApplication,
+ listClients,
+ getCurrentUser,
+ getServerHealth,
+ customApiCall,
+ ],
triggers: [],
});
diff --git a/packages/pieces/community/gotify/src/lib/actions/create-application.ts b/packages/pieces/community/gotify/src/lib/actions/create-application.ts
new file mode 100644
index 00000000000..58387719443
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/create-application.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const createApplication = createAction({
+ auth: gotifyAuth,
+ name: 'create_application',
+ classification: 'WRITE',
+ displayName: 'Create Application',
+ description: 'Create a Gotify application.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Gotify application (name, optional description, optional default priority 0-10) and returns it with its id and its secret app token. Needs the Client Token. Not idempotent: each call creates another application, even with the same name.',
+ idempotent: false,
+ },
+ outputSchema: gotifyOutputSchemas.createdApplication,
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ description: Property.ShortText({ displayName: 'Description', required: false }),
+ defaultPriority: Property.Number({
+ displayName: 'Default Priority',
+ description: 'Priority (0-10) used for messages sent without one.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const name = gotifyClient.optionalText(propsValue.name);
+ if (name === undefined) {
+ throw new Error('Name is required.');
+ }
+ const defaultPriority = gotifyClient.parseOptionalInt({ value: propsValue.defaultPriority, label: 'Default Priority', min: 0, max: 10 });
+ const description = gotifyClient.optionalText(propsValue.description);
+ return gotifyClient.request({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/application',
+ tokenKind: 'client',
+ body: {
+ name,
+ ...(description !== undefined ? { description } : {}),
+ ...(defaultPriority !== undefined ? { defaultPriority } : {}),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/custom-api-call.ts b/packages/pieces/community/gotify/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..687fc3b13f6
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,75 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+
+export const customApiCall = createAction({
+ auth: gotifyAuth,
+ name: 'custom_api_call',
+ classification: 'WRITE',
+ displayName: 'Custom API Call',
+ description: 'Make a request to any Gotify API endpoint with the Client Token.',
+ audience: 'human',
+ props: {
+ path: Property.ShortText({
+ displayName: 'Path',
+ description: 'Endpoint path on your Gotify server, for example /message or /application/1.',
+ required: true,
+ }),
+ method: Property.StaticDropdown({
+ displayName: 'Method',
+ required: true,
+ defaultValue: HttpMethod.GET,
+ options: {
+ options: [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE].map((method) => ({
+ label: method,
+ value: method,
+ })),
+ },
+ }),
+ queryParams: Property.Object({ displayName: 'Query Parameters', required: false }),
+ body: Property.Json({ displayName: 'Body', description: 'JSON body (ignored for GET).', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const path = parsePath(propsValue.path);
+ const method = parseMethod(propsValue.method);
+ const query = Object.fromEntries(
+ Object.entries(propsValue.queryParams ?? {})
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => [key, typeof value === 'number' ? value : String(value)]),
+ );
+ const hasBody = method !== HttpMethod.GET && propsValue.body !== undefined && propsValue.body !== null;
+ const body = await gotifyClient.request({
+ auth: auth.props,
+ method,
+ path,
+ query,
+ body: hasBody ? propsValue.body : undefined,
+ tokenKind: 'client',
+ });
+ return { body };
+ },
+});
+
+function parsePath(value: unknown): string {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (!text.startsWith('/') || text.startsWith('//')) {
+ throw new Error('Path must start with a single "/", for example /message. Full URLs are not allowed.');
+ }
+ if (/[?#\\]/.test(text)) {
+ throw new Error('Path must not contain "?", "#" or "\\". Use Query Parameters for the query string.');
+ }
+ if (text.split('/').some((part) => part === '..' || part === '.' || /^%2e/i.test(part))) {
+ throw new Error('Path must not contain relative segments.');
+ }
+ return text;
+}
+
+function parseMethod(value: unknown): HttpMethod {
+ const allowed: string[] = [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE];
+ const method = Object.values(HttpMethod).find((m) => m === value);
+ if (!method || !allowed.includes(method)) {
+ throw new Error('Method must be GET, POST, PUT, PATCH or DELETE.');
+ }
+ return method;
+}
diff --git a/packages/pieces/community/gotify/src/lib/actions/delete-application-messages.ts b/packages/pieces/community/gotify/src/lib/actions/delete-application-messages.ts
new file mode 100644
index 00000000000..d4ba3e059d7
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/delete-application-messages.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const deleteApplicationMessages = createAction({
+ auth: gotifyAuth,
+ name: 'delete_application_messages',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Application Messages',
+ description: 'Delete all messages of one application.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes every message of one Gotify application, by its numeric application id (from List Applications). The application itself is kept. Needs the Client Token. Fails if the application does not exist; repeating it on an existing application changes nothing more.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.deleteApplicationMessages,
+ props: {
+ applicationId: Property.ShortText({
+ displayName: 'Application ID',
+ description: 'Numeric ID of the application whose messages are deleted.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const applicationId = gotifyClient.parseId({ value: propsValue.applicationId, label: 'Application ID' });
+ await gotifyClient.request({
+ auth: auth.props,
+ method: HttpMethod.DELETE,
+ path: `/application/${applicationId}/message`,
+ tokenKind: 'client',
+ });
+ return { applicationId, deleted: true };
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/delete-application.ts b/packages/pieces/community/gotify/src/lib/actions/delete-application.ts
new file mode 100644
index 00000000000..23d6390ea0f
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/delete-application.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { GotifyApiError, gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const deleteApplication = createAction({
+ auth: gotifyAuth,
+ name: 'delete_application',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Application',
+ description: 'Delete an application and all of its messages.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a Gotify application by numeric id, together with all its messages; its app token stops working. Needs the Client Token. A repeat call on an application that no longer exists returns deleted=false, alreadyDeleted=true instead of failing.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.deleteApplication,
+ props: {
+ applicationId: Property.ShortText({ displayName: 'Application ID', required: true }),
+ },
+ async run({ auth, propsValue }) {
+ const id = gotifyClient.parseId({ value: propsValue.applicationId, label: 'Application ID' });
+ try {
+ await gotifyClient.request({ auth: auth.props, method: HttpMethod.DELETE, path: `/application/${id}`, tokenKind: 'client' });
+ return { id, deleted: true, alreadyDeleted: false };
+ } catch (error) {
+ if (error instanceof GotifyApiError && error.status === 404) {
+ return { id, deleted: false, alreadyDeleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/delete-message.ts b/packages/pieces/community/gotify/src/lib/actions/delete-message.ts
new file mode 100644
index 00000000000..328f0865896
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/delete-message.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { GotifyApiError, gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const deleteMessage = createAction({
+ auth: gotifyAuth,
+ name: 'delete_message',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Message',
+ description: 'Delete one message by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Gotify message by its numeric id (from List Messages). Needs the Client Token. A repeat call on a message that no longer exists returns deleted=false, alreadyDeleted=true instead of failing.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.deleteMessage,
+ props: {
+ messageId: Property.ShortText({
+ displayName: 'Message ID',
+ description: 'Numeric ID of the message to delete.',
+ required: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const id = gotifyClient.parseId({ value: propsValue.messageId, label: 'Message ID' });
+ try {
+ await gotifyClient.request({ auth: auth.props, method: HttpMethod.DELETE, path: `/message/${id}`, tokenKind: 'client' });
+ return { id, deleted: true, alreadyDeleted: false };
+ } catch (error) {
+ if (error instanceof GotifyApiError && error.status === 404) {
+ return { id, deleted: false, alreadyDeleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/get-current-user.ts b/packages/pieces/community/gotify/src/lib/actions/get-current-user.ts
new file mode 100644
index 00000000000..7ec43fc420f
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/get-current-user.ts
@@ -0,0 +1,23 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const getCurrentUser = createAction({
+ auth: gotifyAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Current User',
+ description: 'Get the Gotify user of the Client Token.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns the Gotify user that owns the connection\'s Client Token (id, name, admin flag). Needs the Client Token. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.currentUser,
+ props: {},
+ async run({ auth }) {
+ return gotifyClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/current/user', tokenKind: 'client' });
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/get-server-health.ts b/packages/pieces/community/gotify/src/lib/actions/get-server-health.ts
new file mode 100644
index 00000000000..a5756804561
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/get-server-health.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { GotifyApiError, gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const getServerHealth = createAction({
+ auth: gotifyAuth,
+ name: 'get_server_health',
+ classification: 'READ',
+ displayName: 'Get Server Health',
+ description: 'Get the health and version of the Gotify server.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Checks the connected Gotify server: health and database status ("green" when fine; an unhealthy server returns "orange"/"red" instead of failing) plus version, commit and build date. Needs no token. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.serverHealth,
+ props: {},
+ async run({ auth }) {
+ const health = await gotifyClient
+ .request({ auth: auth.props, method: HttpMethod.GET, path: '/health', tokenKind: 'none' })
+ .catch((error: unknown) => {
+ if (error instanceof GotifyApiError && error.status === 500 && gotifyClient.isRecord(error.responseBody)) {
+ return error.responseBody;
+ }
+ throw error;
+ });
+ const version = await gotifyClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/version', tokenKind: 'none' });
+ const h = gotifyClient.isRecord(health) ? health : {};
+ const v = gotifyClient.isRecord(version) ? version : {};
+ return {
+ health: h['health'] ?? null,
+ database: h['database'] ?? null,
+ version: v['version'] ?? null,
+ commit: v['commit'] ?? null,
+ buildDate: v['buildDate'] ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/list-applications.ts b/packages/pieces/community/gotify/src/lib/actions/list-applications.ts
new file mode 100644
index 00000000000..b5c4e3f34ec
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/list-applications.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const listApplications = createAction({
+ auth: gotifyAuth,
+ name: 'list_applications',
+ classification: 'SEARCH',
+ displayName: 'List Applications',
+ description: 'List the applications of the connected Gotify user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every Gotify application of the connected user (id, name, description, defaultPriority, lastUsed). App tokens are not returned. Needs the Client Token. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.listApplications,
+ props: {},
+ async run({ auth }) {
+ const body = await gotifyClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/application', tokenKind: 'client' });
+ const applications = gotifyClient.arrayOf(body).map((app) => gotifyClient.withoutToken(app));
+ return { applications, count: applications.length };
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/list-clients.ts b/packages/pieces/community/gotify/src/lib/actions/list-clients.ts
new file mode 100644
index 00000000000..f73b10d3584
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/list-clients.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const listClients = createAction({
+ auth: gotifyAuth,
+ name: 'list_clients',
+ classification: 'SEARCH',
+ displayName: 'List Clients',
+ description: 'List the clients (devices) of the connected Gotify user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Gotify clients (phones, browsers, integrations that receive messages) of the connected user with id, name and lastUsed. Client tokens are not returned. Needs the Client Token. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.listClients,
+ props: {},
+ async run({ auth }) {
+ const body = await gotifyClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/client', tokenKind: 'client' });
+ const clients = gotifyClient.arrayOf(body).map((client) => gotifyClient.withoutToken(client));
+ return { clients, count: clients.length };
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/list-messages.ts b/packages/pieces/community/gotify/src/lib/actions/list-messages.ts
new file mode 100644
index 00000000000..a6570a21f5d
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/list-messages.ts
@@ -0,0 +1,63 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const listMessages = createAction({
+ auth: gotifyAuth,
+ name: 'list_messages',
+ classification: 'SEARCH',
+ displayName: 'List Messages',
+ description: 'List messages, newest first, optionally for one application.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Gotify messages newest first (all applications, or one application when applicationId is given). Returns up to limit (1-200, default 100) messages plus hasMore and nextSince; pass nextSince back as since to get the next older page. Needs the Client Token. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.listMessages,
+ props: {
+ applicationId: Property.ShortText({
+ displayName: 'Application ID',
+ description: 'Only list messages of this application. Empty = all.',
+ required: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of messages to return (1-200). Default 100.',
+ required: false,
+ }),
+ since: Property.Number({
+ displayName: 'Since',
+ description: 'Only messages with a lower ID (nextSince of the previous page).',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const applicationText = gotifyClient.optionalText(propsValue.applicationId);
+ const applicationId =
+ applicationText === undefined ? undefined : gotifyClient.parseId({ value: applicationText, label: 'Application ID' });
+ const limit = gotifyClient.parseOptionalInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 200 }) ?? 100;
+ const since = gotifyClient.parseOptionalInt({ value: propsValue.since, label: 'Since', min: 0, max: Number.MAX_SAFE_INTEGER });
+ const body = await gotifyClient.request({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: applicationId === undefined ? '/message' : `/application/${applicationId}/message`,
+ query: { limit, since },
+ tokenKind: 'client',
+ });
+ const record = gotifyClient.isRecord(body) ? body : {};
+ const paging = gotifyClient.isRecord(record['paging']) ? record['paging'] : {};
+ const messages = gotifyClient.arrayOf(record['messages']);
+ const next = paging['next'];
+ const hasMore = typeof next === 'string' && next !== '';
+ const pagingSince = paging['since'];
+ return {
+ messages,
+ count: messages.length,
+ hasMore,
+ nextSince: hasMore && typeof pagingSince === 'number' ? pagingSince : null,
+ };
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/actions/send-notification.ts b/packages/pieces/community/gotify/src/lib/actions/send-notification.ts
index 6820b8d2404..f81a6d20c54 100644
--- a/packages/pieces/community/gotify/src/lib/actions/send-notification.ts
+++ b/packages/pieces/community/gotify/src/lib/actions/send-notification.ts
@@ -1,15 +1,22 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
export const sendNotification = createAction({
auth: gotifyAuth,
name: 'send_notification',
classification: 'WRITE',
displayName: 'Send Notification',
- description: 'Send a notification to gotify',
+ description: 'Send a push notification through your Gotify server.',
audience: 'both',
- aiMetadata: { description: 'Sends a push notification (title, message, optional 0-10 priority) to a self-hosted Gotify server via its message API. Choose this to alert a user or channel through their Gotify instance configured in the connection. Not idempotent: each call posts a new message, so repeating it delivers duplicate notifications.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Sends a push notification (title, message, optional 0-10 priority, optional Markdown rendering, click URL and big image URL) to the self-hosted Gotify server in the connection, using its App Token. Returns the created message with its id. Not idempotent: each call posts a new message, so repeating it delivers a duplicate notification.',
+ idempotent: false,
+ },
+ outputSchema: gotifyOutputSchemas.message,
props: {
title: Property.ShortText({
displayName: 'Title',
@@ -23,27 +30,71 @@ export const sendNotification = createAction({
}),
priority: Property.Number({
displayName: 'Priority',
- description:
- 'The priority of the notification (0-10). 0 is lowest priority.',
+ description: '0 (lowest) to 10. Empty uses the application default.',
+ required: false,
+ }),
+ markdown: Property.Checkbox({
+ displayName: 'Render as Markdown',
+ description: 'Ask Gotify clients to render the message as Markdown.',
+ required: false,
+ defaultValue: false,
+ }),
+ click_url: Property.ShortText({
+ displayName: 'Click URL',
+ description: 'URL opened when the notification is tapped (http or https).',
+ required: false,
+ }),
+ big_image_url: Property.ShortText({
+ displayName: 'Big Image URL',
+ description: 'Image shown in the expanded notification on Android (http or https).',
required: false,
}),
},
async run({ auth, propsValue }) {
- const baseUrl = auth.props.base_url.replace(/\/$/, '');
- const appToken = auth.props.app_token;
-
- const title = propsValue.title;
- const message = propsValue.message;
- const priority = propsValue.priority;
-
- return await httpClient.sendRequest({
+ const message = typeof propsValue.message === 'string' ? propsValue.message : '';
+ if (message.trim() === '') {
+ throw new Error('Message is required.');
+ }
+ const priority = gotifyClient.parseOptionalInt({ value: propsValue.priority, label: 'Priority', min: 0, max: 10 });
+ const clickUrl = webUrl({ value: propsValue.click_url, label: 'Click URL' });
+ const bigImageUrl = webUrl({ value: propsValue.big_image_url, label: 'Big Image URL' });
+ const extras = {
+ ...(propsValue.markdown === true ? { 'client::display': { contentType: 'text/markdown' } } : {}),
+ ...(clickUrl !== undefined || bigImageUrl !== undefined
+ ? {
+ 'client::notification': {
+ ...(clickUrl !== undefined ? { click: { url: clickUrl } } : {}),
+ ...(bigImageUrl !== undefined ? { bigImageUrl } : {}),
+ },
+ }
+ : {}),
+ };
+ return gotifyClient.request({
+ auth: auth.props,
method: HttpMethod.POST,
- url: `${baseUrl}/message?token=${appToken}`,
+ path: '/message',
+ tokenKind: 'app',
body: {
- title,
+ title: propsValue.title,
message,
- ...(priority && { priority: +priority }),
+ ...(priority !== undefined ? { priority } : {}),
+ ...(Object.keys(extras).length > 0 ? { extras } : {}),
},
});
},
});
+
+function webUrl({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = gotifyClient.optionalText(value);
+ if (text === undefined) return undefined;
+ let parsed: URL;
+ try {
+ parsed = new URL(text);
+ } catch {
+ throw new Error(`${label} must be a full http or https URL.`);
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error(`${label} must be a full http or https URL.`);
+ }
+ return text;
+}
diff --git a/packages/pieces/community/gotify/src/lib/actions/update-application.ts b/packages/pieces/community/gotify/src/lib/actions/update-application.ts
new file mode 100644
index 00000000000..ffd0ae49568
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/actions/update-application.ts
@@ -0,0 +1,58 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gotifyAuth } from '../auth';
+import { gotifyClient } from '../common/client';
+import { gotifyOutputSchemas } from '../common/output-schemas';
+
+export const updateApplication = createAction({
+ auth: gotifyAuth,
+ name: 'update_application',
+ classification: 'WRITE',
+ displayName: 'Update Application',
+ description:
+ 'Change the name, description or default priority of an application. Gotify replaces all three fields on every update, so fields you leave empty are re-sent with the values read just before the update; do not run two updates of the same application at the same time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates a Gotify application by numeric id: only the fields you pass change (name, description, defaultPriority 0-10); set clearDescription=true to blank the description. Omitted fields keep their current value: Gotify has no partial update or version check, so the action reads the application and re-sends all three fields; concurrent updates of the same application can overwrite each other, so run them one at a time. Needs the Client Token. Idempotent: the same input gives the same end state. Returns the application without its token.',
+ idempotent: true,
+ },
+ outputSchema: gotifyOutputSchemas.application,
+ props: {
+ applicationId: Property.ShortText({ displayName: 'Application ID', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ description: Property.ShortText({ displayName: 'Description', required: false }),
+ clearDescription: Property.Checkbox({ displayName: 'Clear Description', required: false, defaultValue: false }),
+ defaultPriority: Property.Number({ displayName: 'Default Priority', description: '0-10', required: false }),
+ },
+ async run({ auth, propsValue }) {
+ const id = gotifyClient.parseId({ value: propsValue.applicationId, label: 'Application ID' });
+ const name = gotifyClient.optionalText(propsValue.name);
+ const description = gotifyClient.optionalText(propsValue.description);
+ const defaultPriority = gotifyClient.parseOptionalInt({ value: propsValue.defaultPriority, label: 'Default Priority', min: 0, max: 10 });
+ const clearDescription = propsValue.clearDescription === true;
+ if (clearDescription && description !== undefined) {
+ throw new Error('Use either Description or Clear Description, not both.');
+ }
+ if (name === undefined && description === undefined && defaultPriority === undefined && !clearDescription) {
+ throw new Error('Give at least one field to change.');
+ }
+ const apps = await gotifyClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/application', tokenKind: 'client' });
+ const current = gotifyClient.arrayOf(apps).find((app) => gotifyClient.isRecord(app) && app['id'] === id);
+ if (!gotifyClient.isRecord(current)) {
+ throw new Error(`Application ${id} was not found for this Gotify user.`);
+ }
+ const updated = await gotifyClient.request({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: `/application/${id}`,
+ tokenKind: 'client',
+ body: {
+ name: name ?? current['name'],
+ description: clearDescription ? '' : description ?? current['description'] ?? '',
+ defaultPriority: defaultPriority ?? current['defaultPriority'] ?? 0,
+ },
+ });
+ return gotifyClient.withoutToken(updated);
+ },
+});
diff --git a/packages/pieces/community/gotify/src/lib/auth.ts b/packages/pieces/community/gotify/src/lib/auth.ts
index efcf554d883..66f97f645e1 100644
--- a/packages/pieces/community/gotify/src/lib/auth.ts
+++ b/packages/pieces/community/gotify/src/lib/auth.ts
@@ -1,25 +1,70 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { GotifyApiError, gotifyClient } from './common/client';
export const gotifyAuth = PieceAuth.CustomAuth({
description: `
- To obtain a token:
+ To connect Gotify:
- 1. Log in to your Gotify instance.
- 2. Click on Apps
- 3. Select the Eye icon in the same row as your App to copy your token, or CREATE APPLICATION if you do not have one app yet.
- 4. Copy your access token & and paste them into the fields below.
+ 1. Log in to your Gotify web UI.
+ 2. Open **Apps**, create an application (or pick one) and copy its token into **App Token**. It is used to send notifications.
+ 3. Optional: open **Clients**, create a client and copy its token into **Client Token**. It is needed to read and delete messages and to manage applications.
`,
props: {
base_url: Property.ShortText({
displayName: 'Server URL',
- description: 'Gotify Instance URL',
+ description: 'The address of your Gotify server, e.g. https://gotify.example.com',
required: true,
}),
app_token: PieceAuth.SecretText({
displayName: 'App Token',
- description: 'Gotify App Token',
+ description: 'Token of a Gotify application. Used to send notifications.',
required: true,
}),
+ client_token: PieceAuth.SecretText({
+ displayName: 'Client Token',
+ description: 'Token of a Gotify client. Needed to read or delete messages and manage applications.',
+ required: false,
+ }),
+ },
+ validate: async ({ auth }) => {
+ try {
+ gotifyClient.normalizeBaseUrl(auth.base_url);
+ gotifyClient.appTokenOf(auth);
+ } catch (error) {
+ return { valid: false, error: error instanceof Error ? error.message : 'Invalid connection.' };
+ }
+ try {
+ const health = await gotifyClient.request({ auth, method: HttpMethod.GET, path: '/health', tokenKind: 'none' });
+ if (!gotifyClient.isRecord(health) || typeof health['health'] !== 'string') {
+ return { valid: false, error: 'The Server URL does not point to a Gotify server.' };
+ }
+ } catch (error) {
+ return {
+ valid: false,
+ error: error instanceof Error ? `Could not reach the Gotify server: ${error.message}` : 'Could not reach the Gotify server.',
+ };
+ }
+ if (!auth.client_token || auth.client_token.trim() === '') {
+ return { valid: true };
+ }
+ try {
+ const apps = await gotifyClient.request({ auth, method: HttpMethod.GET, path: '/application', tokenKind: 'client' });
+ const appToken = gotifyClient.appTokenOf(auth);
+ const known = gotifyClient.arrayOf(apps).some((app) => gotifyClient.isRecord(app) && app['token'] === appToken);
+ if (!known) {
+ return { valid: false, error: 'The App Token does not belong to the user of this Client Token.' };
+ }
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof GotifyApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid Client Token.' };
+ }
+ return {
+ valid: false,
+ error: error instanceof Error ? `Could not check the Client Token: ${error.message}` : 'Could not check the Client Token.',
+ };
+ }
},
required: true,
});
diff --git a/packages/pieces/community/gotify/src/lib/common/client.ts b/packages/pieces/community/gotify/src/lib/common/client.ts
new file mode 100644
index 00000000000..580ad1d2fdb
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/common/client.ts
@@ -0,0 +1,230 @@
+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';
+
+const REQUEST_TIMEOUT_MS = 30_000;
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class GotifyApiError extends Error {
+ constructor(
+ message: string,
+ public readonly status: number,
+ public readonly responseBody: unknown,
+ ) {
+ super(message);
+ this.name = 'GotifyApiError';
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function normalizeBaseUrl(raw: unknown): string {
+ const text = typeof raw === 'string' ? raw.trim() : '';
+ if (!text) {
+ throw new Error('The Gotify connection has no Server URL.');
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(text);
+ } catch {
+ throw new Error('The Gotify Server URL is not a valid URL. Use a full address like https://gotify.example.com.');
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error('The Gotify Server URL must start with http:// or https://.');
+ }
+ if (parsed.username || parsed.password) {
+ throw new Error('The Gotify Server URL must not contain a username or password.');
+ }
+ if (parsed.search || parsed.hash || text.includes('?') || text.includes('#')) {
+ throw new Error('The Gotify Server URL must not contain a query string or fragment.');
+ }
+ const path = parsed.pathname.replace(/\/+$/, '');
+ if (path.split('/').some((part) => part === '..' || part === '.')) {
+ throw new Error('The Gotify Server URL must not contain relative path segments.');
+ }
+ return `${parsed.origin}${path}`;
+}
+
+function tokenOf(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function appTokenOf(auth: GotifyAuthValue): string {
+ const token = tokenOf(auth.app_token);
+ if (!token) {
+ throw new Error('The Gotify connection has no App Token.');
+ }
+ return token;
+}
+
+function clientTokenOf(auth: GotifyAuthValue): string {
+ const token = tokenOf(auth.client_token);
+ if (!token) {
+ throw new Error(
+ 'This action needs a Client Token. Add one to the Gotify connection (Gotify web UI > Clients > Create Client). The App Token can only send messages.',
+ );
+ }
+ return token;
+}
+
+function isSameOrigin({ url, baseUrl }: { url: string; baseUrl: string }): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.username || parsed.password) return false;
+ const base = new URL(baseUrl);
+ if (parsed.origin !== base.origin) return false;
+ const basePath = base.pathname.replace(/\/+$/, '');
+ if (basePath === '') return true;
+ return parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`);
+}
+
+function vendorMessage(body: unknown): string {
+ if (isRecord(body)) {
+ const description = body['errorDescription'];
+ const error = body['error'];
+ if (typeof description === 'string' && description.trim()) return description.trim();
+ if (typeof error === 'string' && error.trim()) return error.trim();
+ }
+ if (typeof body === 'string' && body.trim()) return body.trim().slice(0, 300);
+ return 'request failed';
+}
+
+function hintFor({ status, tokenKind }: { status: number; tokenKind: TokenKind }): string {
+ if (status === 401) {
+ return tokenKind === 'app'
+ ? ' Check the App Token in the Gotify connection.'
+ : ' Check the Client Token in the Gotify connection (an App Token does not work here).';
+ }
+ if (status === 403) return ' The token is valid but not allowed to do this (some endpoints need an admin user\'s client).';
+ return '';
+}
+
+function toApiError({ status, body, tokenKind }: { status: number; body: unknown; tokenKind: TokenKind }): GotifyApiError {
+ const base = status >= 300 && status < 400 ? 'unexpected redirect' : vendorMessage(body);
+ return new GotifyApiError(`Gotify API error (${status}): ${base}.${hintFor({ status, tokenKind })}`, status, body);
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function failureOf(error: unknown): { status: number; body: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'] } : null;
+}
+
+async function request({ auth, method, path, query, body, tokenKind }: GotifyRequest): Promise<unknown> {
+ const baseUrl = normalizeBaseUrl(auth.base_url);
+ const headers: Record<string, string> = { accept: 'application/json' };
+ if (tokenKind === 'app') headers['x-gotify-key'] = appTokenOf(auth);
+ if (tokenKind === 'client') headers['x-gotify-key'] = clientTokenOf(auth);
+ const hasBody = body !== undefined;
+ if (hasBody) headers['content-type'] = 'application/json';
+ const dispatcher = await verifiedTls();
+ let status: number;
+ let responseBody: unknown;
+ try {
+ const response: HttpResponse = await httpClient.sendRequest(
+ {
+ method,
+ url: `${baseUrl}${path}`,
+ headers,
+ queryParams: buildQuery(query),
+ body: hasBody ? body : undefined,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ },
+ { dispatcher },
+ );
+ status = response.status;
+ responseBody = response.body;
+ } catch (error) {
+ const failure = failureOf(error);
+ if (!failure) throw error;
+ status = failure.status;
+ responseBody = failure.body;
+ }
+ if (status < 200 || status >= 300) {
+ throw toApiError({ status, body: responseBody, tokenKind });
+ }
+ return responseBody;
+}
+
+function buildQuery(query?: Record<string, string | number | undefined>): QueryParams {
+ return Object.fromEntries(
+ Object.entries(query ?? {})
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+function parseId({ value, label }: { value: unknown; label: string }): number {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!/^\d+$/.test(text) || Number(text) < 1 || !Number.isSafeInteger(Number(text))) {
+ throw new Error(`${label} must be a positive whole number (the numeric Gotify ID).`);
+ }
+ return Number(text);
+}
+
+function parseOptionalInt({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return parsed;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') return undefined;
+ const text = value.trim();
+ return text === '' ? undefined : text;
+}
+
+function withoutToken(value: unknown): Record<string, unknown> {
+ if (!isRecord(value)) return {};
+ return Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'token'));
+}
+
+function arrayOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+export const gotifyClient = {
+ request,
+ normalizeBaseUrl,
+ isSameOrigin,
+ clientTokenOf,
+ appTokenOf,
+ parseId,
+ parseOptionalInt,
+ optionalText,
+ withoutToken,
+ arrayOf,
+ isRecord,
+};
+
+type TokenKind = 'app' | 'client' | 'none';
+
+export type GotifyAuthValue = {
+ base_url: string;
+ app_token: string;
+ client_token?: string;
+};
+
+export type GotifyRequest = {
+ auth: GotifyAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, string | number | undefined>;
+ body?: unknown;
+ tokenKind: TokenKind;
+};
diff --git a/packages/pieces/community/gotify/src/lib/common/output-schemas.ts b/packages/pieces/community/gotify/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..c05eeb8a0ce
--- /dev/null
+++ b/packages/pieces/community/gotify/src/lib/common/output-schemas.ts
@@ -0,0 +1,97 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const messageFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Message ID', format: 'number' },
+ { key: 'appid', label: 'Application ID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'message', label: 'Message' },
+ { key: 'priority', label: 'Priority', format: 'number' },
+ { key: 'date', label: 'Date', format: 'datetime' },
+ { key: 'extras', label: 'Extras', description: 'Gotify extras such as client::display.contentType, when the message has any.' },
+];
+
+const applicationFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Application ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'defaultPriority', label: 'Default Priority', format: 'number' },
+ { key: 'internal', label: 'Internal', format: 'boolean' },
+ { key: 'image', label: 'Image Path' },
+ { key: 'lastUsed', label: 'Last Used', format: 'datetime' },
+];
+
+export const gotifyOutputSchemas = {
+ message: { fields: messageFields } satisfies OutputSchema,
+ listMessages: {
+ fields: [
+ { key: 'messages', label: 'Messages', labelKey: 'title', listItems: messageFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ { key: 'nextSince', label: 'Next Since', format: 'number', description: 'Pass as Since to fetch the next (older) page. Null when there is no more.' },
+ ],
+ } satisfies OutputSchema,
+ deleteMessage: {
+ fields: [
+ { key: 'id', label: 'Message ID', format: 'number' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ deleteApplicationMessages: {
+ fields: [
+ { key: 'applicationId', label: 'Application ID', format: 'number' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ application: { fields: applicationFields } satisfies OutputSchema,
+ createdApplication: {
+ fields: [
+ ...applicationFields,
+ { key: 'token', label: 'App Token', description: 'Secret token of the new application, used to send messages through it.' },
+ ],
+ } satisfies OutputSchema,
+ listApplications: {
+ fields: [
+ { key: 'applications', label: 'Applications', labelKey: 'name', listItems: applicationFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ deleteApplication: {
+ fields: [
+ { key: 'id', label: 'Application ID', format: 'number' },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ listClients: {
+ fields: [
+ {
+ key: 'clients',
+ label: 'Clients',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Client ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'lastUsed', label: 'Last Used', format: 'datetime' },
+ ],
+ },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ currentUser: {
+ fields: [
+ { key: 'id', label: 'User ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'admin', label: 'Admin', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ serverHealth: {
+ fields: [
+ { key: 'health', label: 'Health' },
+ { key: 'database', label: 'Database' },
+ { key: 'version', label: 'Version' },
+ { key: 'commit', label: 'Commit' },
+ { key: 'buildDate', label: 'Build Date' },
+ ],
+ } satisfies OutputSchema,
+};
diff --git a/packages/pieces/community/gotify/test/gotify.test.ts b/packages/pieces/community/gotify/test/gotify.test.ts
new file mode 100644
index 00000000000..a573e0ca84e
--- /dev/null
+++ b/packages/pieces/community/gotify/test/gotify.test.ts
@@ -0,0 +1,222 @@
+import { httpClient } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { gotify } from '../src';
+import { GotifyApiError, gotifyClient } from '../src/lib/common/client';
+
+const auth = { props: { base_url: 'https://gotify.example.com/', app_token: 'app-secret', client_token: 'client-secret' } };
+
+function action(name: string) {
+ const found = gotify.actions()[name];
+ if (!found) throw new Error(`missing ${name}`);
+ return found;
+}
+
+function mockResponse(body: unknown) {
+ return vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body });
+}
+
+function runAction({ name, propsValue = {}, connection = auth }: { name: string; propsValue?: Record<string, unknown>; connection?: unknown }) {
+ const context = { auth: connection, propsValue };
+ return Reflect.apply(action(name).run, undefined, [context]);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('normalizeBaseUrl', () => {
+ it('strips trailing slashes and keeps a subpath', () => {
+ expect(gotifyClient.normalizeBaseUrl('https://h.example.com/gotify///')).toBe('https://h.example.com/gotify');
+ expect(gotifyClient.normalizeBaseUrl(' http://localhost:8081/ ')).toBe('http://localhost:8081');
+ });
+ it.each([
+ 'ftp://h.example.com',
+ 'https://user:[email protected]',
+ 'https://h.example.com/?token=x',
+ 'https://h.example.com/#x',
+ 'h.example.com',
+ '',
+ ])('rejects %s', (value) => {
+ expect(() => gotifyClient.normalizeBaseUrl(value)).toThrow();
+ });
+});
+
+describe('isSameOrigin', () => {
+ it('rejects lookalike hosts and other prefixes', () => {
+ const baseUrl = 'https://gotify.example.com/g';
+ expect(gotifyClient.isSameOrigin({ url: 'https://gotify.example.com/g/message', baseUrl })).toBe(true);
+ expect(gotifyClient.isSameOrigin({ url: 'https://gotify.example.com.evil.io/g/message', baseUrl })).toBe(false);
+ expect(gotifyClient.isSameOrigin({ url: 'https://gotify.example.com/other', baseUrl })).toBe(false);
+ expect(gotifyClient.isSameOrigin({ url: 'https://[email protected]/g', baseUrl })).toBe(false);
+ });
+});
+
+describe('parseId', () => {
+ it('accepts numeric strings and rejects others', () => {
+ expect(gotifyClient.parseId({ value: ' 12 ', label: 'ID' })).toBe(12);
+ expect(() => gotifyClient.parseId({ value: '1/../x', label: 'ID' })).toThrow();
+ expect(() => gotifyClient.parseId({ value: '0', label: 'ID' })).toThrow();
+ });
+});
+
+describe('send_notification', () => {
+ it('sends the token in a header, keeps priority 0 and builds extras', async () => {
+ const spy = mockResponse({ id: 1, appid: 1, message: 'm', title: 't', priority: 0, date: '2026-10-14T00:00:00Z' });
+ const result = await runAction({ name: 'send_notification', propsValue: {
+ title: 't',
+ message: 'm',
+ priority: 0,
+ markdown: true,
+ click_url: 'https://example.com',
+ } });
+ const request = spy.mock.calls[0][0];
+ expect(request.url).toBe('https://gotify.example.com/message');
+ expect(request.url).not.toContain('app-secret');
+ expect(request.headers).toMatchObject({ 'x-gotify-key': 'app-secret' });
+ expect(request.body).toEqual({
+ title: 't',
+ message: 'm',
+ priority: 0,
+ extras: { 'client::display': { contentType: 'text/markdown' }, 'client::notification': { click: { url: 'https://example.com' } } },
+ });
+ expect(result).toEqual({ id: 1, appid: 1, message: 'm', title: 't', priority: 0, date: '2026-10-14T00:00:00Z' });
+ });
+ it('omits priority when empty and rejects out of range', async () => {
+ const spy = mockResponse({ id: 2 });
+ await runAction({ name: 'send_notification', propsValue: { title: 't', message: 'm' } });
+ expect(spy.mock.calls[0][0].body).toEqual({ title: 't', message: 'm' });
+ await expect(runAction({ name: 'send_notification', propsValue: { title: 't', message: 'm', priority: 11 } })).rejects.toThrow('Priority');
+ });
+ it('rejects a non-http click url', async () => {
+ mockResponse({});
+ await expect(runAction({ name: 'send_notification', propsValue: { title: 't', message: 'm', click_url: 'javascript:alert(1)' } })).rejects.toThrow('Click URL');
+ });
+});
+
+describe('error mapping', () => {
+ it('maps a 401 to GotifyApiError with responseBody', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue({
+ response: { status: 401, body: { error: 'Unauthorized', errorCode: 401, errorDescription: 'bad token' } },
+ });
+ const error = await runAction({ name: 'get_current_user' }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(GotifyApiError);
+ expect(error).toMatchObject({ status: 401, responseBody: { errorDescription: 'bad token' } });
+ });
+ it('needs a client token for read actions', async () => {
+ const spy = mockResponse({});
+ await expect(runAction({ name: 'list_clients', connection: { props: { ...auth.props, client_token: undefined } } })).rejects.toThrow('Client Token');
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('list_messages', () => {
+ it('uses the application path and returns paging', async () => {
+ const spy = mockResponse({ paging: { next: 'https://x/next', since: 5, size: 1, limit: 1 }, messages: [{ id: 5 }] });
+ const result = await runAction({ name: 'list_messages', propsValue: { applicationId: '3', limit: 1, since: 9 } });
+ const request = spy.mock.calls[0][0];
+ expect(request.url).toBe('https://gotify.example.com/application/3/message');
+ expect(request.queryParams).toEqual({ limit: '1', since: '9' });
+ expect(request.headers).toMatchObject({ 'x-gotify-key': 'client-secret' });
+ expect(result).toEqual({ messages: [{ id: 5 }], count: 1, hasMore: true, nextSince: 5 });
+ });
+ it('reports no more pages without next', async () => {
+ mockResponse({ paging: { since: 0, size: 0, limit: 100 }, messages: [] });
+ expect(await runAction({ name: 'list_messages' })).toEqual({ messages: [], count: 0, hasMore: false, nextSince: null });
+ });
+});
+
+describe('token projection', () => {
+ it('removes tokens from applications and clients', async () => {
+ mockResponse([{ id: 1, name: 'a', token: 'secret' }]);
+ expect(await runAction({ name: 'list_applications' })).toEqual({ applications: [{ id: 1, name: 'a' }], count: 1 });
+ vi.restoreAllMocks();
+ mockResponse([{ id: 1, name: 'c', token: 'secret' }]);
+ expect(await runAction({ name: 'list_clients' })).toEqual({ clients: [{ id: 1, name: 'c' }], count: 1 });
+ });
+});
+
+describe('deletes', () => {
+ it('treats 404 on delete_message as already deleted', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue({ response: { status: 404, body: { error: 'Not Found' } } });
+ expect(await runAction({ name: 'delete_message', propsValue: { messageId: '7' } })).toEqual({ id: 7, deleted: false, alreadyDeleted: true });
+ });
+ it('rethrows other errors', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue({ response: { status: 500, body: 'boom' } });
+ await expect(runAction({ name: 'delete_application', propsValue: { applicationId: '7' } })).rejects.toBeInstanceOf(GotifyApiError);
+ });
+});
+
+describe('update_application', () => {
+ it('merges current values into the PUT body', async () => {
+ const spy = vi
+ .spyOn(httpClient, 'sendRequest')
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: [{ id: 4, name: 'old', description: 'd', defaultPriority: 5, token: 't' }] })
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 4, name: 'new', description: 'd', defaultPriority: 5, token: 't' } });
+ const result = await runAction({ name: 'update_application', propsValue: { applicationId: '4', name: 'new' } });
+ expect(spy.mock.calls[1][0].body).toEqual({ name: 'new', description: 'd', defaultPriority: 5 });
+ expect(result).toEqual({ id: 4, name: 'new', description: 'd', defaultPriority: 5 });
+ });
+ it('refuses an empty update', async () => {
+ const spy = mockResponse([]);
+ await expect(runAction({ name: 'update_application', propsValue: { applicationId: '4' } })).rejects.toThrow('at least one');
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('get_server_health', () => {
+ it('returns the unhealthy status when /health answers 500', async () => {
+ vi.spyOn(httpClient, 'sendRequest')
+ .mockRejectedValueOnce({ response: { status: 500, body: { health: 'orange', database: 'red' } } })
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { version: '2.6.1', commit: 'abc', buildDate: '2024' } });
+ const result = await runAction({ name: 'get_server_health' });
+ expect(result).toEqual({ health: 'orange', database: 'red', version: '2.6.1', commit: 'abc', buildDate: '2024' });
+ });
+
+ it('still throws on other errors', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue({ response: { status: 502, body: 'bad gateway' } });
+ await expect(runAction({ name: 'get_server_health' })).rejects.toBeInstanceOf(GotifyApiError);
+ });
+});
+
+describe('auth validate', () => {
+ it('rejects an app token not owned by the client user', async () => {
+ vi.spyOn(httpClient, 'sendRequest')
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: { health: 'green', database: 'green' } })
+ .mockResolvedValueOnce({ status: 200, headers: {}, body: [{ id: 1, token: 'other' }] });
+ const validate = gotify.auth?.validate;
+ if (!validate) throw new Error('no validate');
+ const result = await Reflect.apply(validate, undefined, [{ auth: auth.props }]);
+ expect(result).toMatchObject({ valid: false });
+ });
+});
+
+describe('custom_api_call', () => {
+ it('sends with the Client Token through the verifying TLS dispatcher', async () => {
+ const spy = mockResponse({ ok: true });
+ const result = await runAction({
+ name: 'custom_api_call',
+ propsValue: { path: '/application', method: 'POST', queryParams: { a: 1 }, body: { name: 'x' } },
+ });
+ const [request, options] = spy.mock.calls[0];
+ expect(request.url).toBe('https://gotify.example.com/application');
+ expect(request.headers).toMatchObject({ 'x-gotify-key': 'client-secret' });
+ expect(request.queryParams).toEqual({ a: '1' });
+ expect(request.body).toEqual({ name: 'x' });
+ expect(request.followRedirects).toBe(false);
+ expect(options?.dispatcher).toBeDefined();
+ expect(result).toEqual({ body: { ok: true } });
+ });
+ it('drops the body on GET', async () => {
+ const spy = mockResponse([]);
+ await runAction({ name: 'custom_api_call', propsValue: { path: '/message', method: 'GET', body: { x: 1 } } });
+ expect(spy.mock.calls[0][0].body).toBeUndefined();
+ });
+ it.each(['https://evil.example.com/x', '//evil.example.com/x', 'message', '/a/../b', '/a/%2e%2e/b', '/a?token=x', '/a\\b'])(
+ 'rejects path %s before any request',
+ async (path) => {
+ const spy = mockResponse({});
+ await expect(runAction({ name: 'custom_api_call', propsValue: { path, method: 'GET' } })).rejects.toThrow();
+ expect(spy).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/packages/pieces/community/gotify/vitest.config.ts b/packages/pieces/community/gotify/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/gotify/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})