Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 237 additions & 0 deletions docs-v2/components/AppSearchDemo.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
"use client";

import {
useState, useEffect, useCallback,
} from "react";
import { styles } from "../utils/componentStyles";
import { generateRequestToken } from "./api";

// Debounce hook
function useDebounce(value, delay) {
const [
debouncedValue,
setDebouncedValue,
] = useState(value);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(handler);
};
}, [
value,
delay,
]);

return debouncedValue;
}

export default function AppSearchDemo() {
const [
searchQuery,
setSearchQuery,
] = useState("");
const [
apps,
setApps,
] = useState([]);
const [
isLoading,
setIsLoading,
] = useState(false);
const [
error,
setError,
] = useState("");
const [
copiedSlug,
setCopiedSlug,
] = useState("");

const debouncedSearchQuery = useDebounce(searchQuery, 300);

const searchApps = useCallback(async (query) => {
if (!query || query.length < 2) {
setApps([]);
return;
}

setIsLoading(true);
setError("");

try {
const requestToken = generateRequestToken();
// Convert spaces to underscores for name_slug searching
const searchQuery = query.replace(/\s+/g, "_");
const response = await fetch(
`/docs/api-demo-connect/apps?q=${encodeURIComponent(searchQuery)}&limit=5`,
{
headers: {
"Content-Type": "application/json",
"X-Request-Token": requestToken,
},
},
);

if (!response.ok) {
throw new Error("Failed to search apps");
}

const data = await response.json();
console.log("App icons:", data.apps.map((app) => ({
name: app.name,
icon: app.icon,
})));
setApps(data.apps);
} catch (err) {
console.error("Error searching apps:", err);
setError("Failed to search apps. Please try again.");
setApps([]);
} finally {
setIsLoading(false);
}
}, []);

useEffect(() => {
searchApps(debouncedSearchQuery);
}, [
debouncedSearchQuery,
searchApps,
]);

async function copyToClipboard(nameSlug) {
try {
await navigator.clipboard.writeText(nameSlug);
setCopiedSlug(nameSlug);
setTimeout(() => setCopiedSlug(""), 2000);
} catch (err) {
console.error("Failed to copy:", err);
}
}

return (
<div className={styles.container}>
<div className={styles.header}>Search for an app</div>
<div className="p-4">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search for an app (e.g., slack, notion, gmail)"
className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500"
/>

{searchQuery.length > 0 && searchQuery.length < 2 && (
<p className={styles.text.muted + " mt-2"}>
Type at least 2 characters to search
</p>
)}

{isLoading && (
<div className="mt-4 text-center">
<p className={styles.text.normal}>Searching...</p>
</div>
)}

{error && (
<div className={styles.statusBox.error}>
<p className="text-sm">{error}</p>
</div>
)}

{apps.length > 0 && !isLoading && (
<div className="mt-4 space-y-3">
{apps.map((app) => (
<div
key={app.id}
className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:border-gray-300 dark:hover:border-gray-600 transition-colors"
>
<div className="flex items-start gap-3">
{app.icon && (
<img
src={app.icon}
alt={app.name}
className="w-10 h-10 rounded"
/>
)}
<div className="flex-1">
<div className="flex items-center gap-2 mb-1 flex-nowrap">
<p className="font-semibold text-base text-gray-800 dark:text-gray-200 flex-shrink-0 m-0">
{app.name}
</p>
<code className="text-sm px-2 py-0.5 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded flex-shrink-0">
{app.name_slug}
</code>
<button
onClick={() => copyToClipboard(app.name_slug)}
className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors flex-shrink-0"
title={copiedSlug === app.name_slug
? "Copied!"
: "Copy app name slug"}
>
{copiedSlug === app.name_slug
? (
<svg className="w-4 h-4 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
)
: (
<svg className="w-4 h-4 text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
)}
</button>
</div>
<p className={styles.text.muted + " line-clamp-2"}>
{app.description}
</p>
{app.categories.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1">
{app.categories.map((category) => (
<span
key={category}
className="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded"
>
{category}
</span>
))}
</div>
)}
</div>
</div>
</div>
))}
</div>
)}

{debouncedSearchQuery.length >= 2 &&
apps.length === 0 &&
!isLoading &&
!error && (
<div className="mt-4 text-center">
<p className={styles.text.muted}>
No apps found for "{debouncedSearchQuery}"
</p>
</div>
)}

<div className="mt-4">
<p className={styles.text.small}>
Browse all available apps at{" "}
<a
href="https://mcp.pipedream.com"
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:text-blue-600"
>
mcp.pipedream.com
</a>
</p>
</div>
</div>
</div>
);
}
8 changes: 8 additions & 0 deletions docs-v2/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,14 @@ export default withNextra({
source: "/api-demo-connect/accounts/:id/",
destination: "/api/demo-connect/accounts/:id",
},
{
source: "/api-demo-connect/apps",
destination: "/api/demo-connect/apps",
},
{
source: "/api-demo-connect/apps/",
destination: "/api/demo-connect/apps",
},
{
source: "/workflows/errors/",
destination: "/workflows/building-workflows/errors/",
Expand Down
83 changes: 83 additions & 0 deletions docs-v2/pages/api/demo-connect/apps.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Search for apps in the Pipedream API

import { createApiHandler } from "./utils";

/**
* Handler for searching apps
*/
async function appsHandler(req, res) {
try {
const {
q, limit = 50,
} = req.query;
Comment on lines +10 to +12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation for the limit parameter.

The limit parameter should be validated to prevent potential abuse or unexpected behavior.

Apply this diff to add proper validation:

 const {
-  q, limit = 50,
+  q, limit = 50,
 } = req.query;

+// Validate limit parameter
+const validatedLimit = Math.min(Math.max(parseInt(limit, 10) || 50, 1), 100);

Then use validatedLimit instead of limit in the params:

-params.append("limit", String(limit));
+params.append("limit", String(validatedLimit));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const {
q, limit = 50,
} = req.query;
const {
q, limit = 50,
} = req.query;
// Validate limit parameter
const validatedLimit = Math.min(Math.max(parseInt(limit, 10) || 50, 1), 100);
params.append("limit", String(validatedLimit));
🤖 Prompt for AI Agents
In docs-v2/pages/api/demo-connect/apps.js around lines 10 to 12, the limit
parameter from req.query lacks validation, which can lead to abuse or unexpected
behavior. Add input validation to ensure limit is a positive integer within an
acceptable range (e.g., 1 to 100). Parse the limit value, check if it is a valid
number within the range, and if not, set a default value like 50. Replace all
uses of limit with the validatedLimit variable to enforce this validation
consistently.


// Build the query parameters
const params = new URLSearchParams();
if (q) params.append("q", q);
params.append("limit", String(limit));
params.append("has_actions", "1"); // Only apps with components

// First get an OAuth token
const tokenResponse = await fetch(
"https://api.pipedream.com/v1/oauth/token",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "client_credentials",
client_id: process.env.PIPEDREAM_CLIENT_ID,
client_secret: process.env.PIPEDREAM_CLIENT_SECRET,
}),
},
);

if (!tokenResponse.ok) {
throw new Error("Failed to authenticate");
}

const { access_token } = await tokenResponse.json();

// Now search for apps
const appsResponse = await fetch(
`https://api.pipedream.com/v1/apps?${params.toString()}`,
{
headers: {
"Authorization": `Bearer ${access_token}`,
"Content-Type": "application/json",
},
},
);

if (!appsResponse.ok) {
throw new Error("Failed to fetch apps");
}

const appsData = await appsResponse.json();

// Format the response with the fields we need
const formattedApps = appsData.data.map((app) => ({
id: app.id,
name: app.name,
name_slug: app.name_slug,
description: app.description,
icon: app.img_src,
categories: app.categories || [],
}));

return res.status(200).json({
apps: formattedApps,
total_count: appsData.page_info?.total_count || formattedApps.length,
});
} catch (error) {
console.error("Error searching apps:", error);
return res.status(500).json({
error: "Failed to search apps",
details: error.message,
});
}
}

// Export the handler wrapped with security checks
export default createApiHandler(appsHandler, "GET");
4 changes: 2 additions & 2 deletions docs-v2/pages/connect/mcp/openai.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Callout, Tabs, Steps } from 'nextra/components'
import TemporaryTokenGenerator from '@/components/TemporaryTokenGenerator'
import AppSearchDemo from '@/components/AppSearchDemo'

# Using Pipedream MCP with OpenAI

Expand Down Expand Up @@ -29,8 +30,7 @@ Click the **Create** button in the **Tools** section, then select **Pipedream**.

#### Select an app

- Select an app you want to use as an MCP server. For example, `notion`, `google_calendar`, `gmail`, or `slack`.
- Check out all of the available apps here: [mcp.pipedream.com](https://mcp.pipedream.com).
<AppSearchDemo />

#### Click **Connect**

Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading